(function() {
    'uses strict';

    /**
     * 用户必须在微信中使用
     * @type {[type]}
     * (/micromessenger/.test(ua))
     */
    var ua = navigator.userAgent.toLowerCase();
    if (!/micromessenger/.test(ua)) {
        console.warn("请您在微信中打开该链接，谢谢！");
        alert("请您在微信中打开该链接，谢谢！");
        return;
    }
    angular.module('weApp', ['ionic', 'LocalStorageModule', 'pasvaz.bindonce', 'weApp.services', 'weApp.controllers', 'weApp.directives'])

            .run(['$rootScope', '$state', '$stateParams', '$ionicPlatform', '$http', 'weAppDataBase', 'localStorageService', '$ionicLoading', 'checkUserPosition', '$q', '$ionicPopup',
                function($rootScope, $state, $stateParams, $ionicPlatform, $http, weAppDataBase, localStorageService, $ionicLoading, checkUserPosition, $q, $ionicPopup) {


                    $rootScope.$on("$stateChangeSuccess", function(event, toState, toParams, fromState, fromParams) {
                        $rootScope.prevState = fromState;
                        $rootScope.prevParams = fromParams;
                        $rootScope.currUrl = toState;
                    });

                    //远程服务器地址
                    //延安
                    /*$rootScope.rootLocation = "http://117.34.118.16:8789/bi";
                     $rootScope.rootAbsoluteUrl = "http://www.16bus.net/wechat";
                     $rootScope.cityCode = "284";
                     $rootScope.cityName = "延安";
                     $rootScope.cityLocation = {
                     lat: "36.591169",
                     lng: "109.495702"
                     };
                     $rootScope.systemName = "易公交";*/
                    // 江门
                    $rootScope.rootLocation = "http://219.130.135.52:8789/bi";
                    $rootScope.rootAbsoluteUrl = "http://mobile.jmqyjt.com/wechat";
                    $rootScope.cityCode = "302";
                    $rootScope.cityName = "江门";
                    $rootScope.cityLocation = {
                        lat: "22.584404",
                        lng: "113.088161"
                    };
                    $rootScope.systemName = "江门智能公交";

                    $rootScope.refreshPerSec = 6500;

                    $rootScope.appReadyPromise = $q.defer();

                    $rootScope.cityNotIn = localStorageService.get("cityNotIn");

                    $rootScope.locationURI = encodeURIComponent(location.href.split('#')[0]);

                    $rootScope.tabs = [
                        {
                            "name": "首页",
                            "herf": "index",
                            "icon": "we-icon-home"
                        }, 
                        {
                            "name": "换乘",
                            "herf": "trans",
                            "icon": "we-icon-huanyihuan"
                        }, 
                        {
                            "name": "收藏",
                            "herf": "favor",
                            "icon": "we-icon-favor"
                        },
                        {
                            "name": "更多",
                            "herf": "more",
                            "icon": "we-icon-more"
                        }
                    ];

                    $rootScope.myAddress = null;
                    $rootScope.siteTimes = null;

                    /**
                     * 微信对接配置
                     */
                    /**
                     * 本地请求微信服务器配置
                     * appId/timestamp/nonceStr/signature
                     */
                    var rootReq = {
                        method: 'post',
                        url: $rootScope.rootLocation + '/wechat/accesstoken/sign',
                        data: {
                            "tokenUrl": $rootScope.locationURI,
                            "cityCode": $rootScope.cityCode
                        }
                    };

                    $http(rootReq)
                            .then(function(wxRegRes) {

                                var wxConfig = wxRegRes.data.data;

                                wx.config({
                                    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                                    appId: wxConfig.appid, // 必填，公众号的唯一标识
                                    timestamp: wxConfig.timestamp, // 必填，生成签名的时间戳
                                    nonceStr: wxConfig.noncestr, // 必填，生成签名的随机串
                                    signature: wxConfig.signature, // 必填，签名，见附录1
                                    jsApiList: ['getLocation', 'hideAllNonBaseMenuItem', 'showMenuItems', 'onMenuShareAppMessage', 'onMenuShareTimeline'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
                                });
                                /**
                                 * 微信配置成功后调用 获取用户地理位置接口
                                 * 该接口返回的为GPS经纬度信息，需要在回调函数中调用百度接口进行经纬度信息转换
                                 */
                                wx.ready(function() {

                                    /**
                                     * 微信中获取用户地理位置信息
                                     */
                                    wx.getLocation({
                                        type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                                        success: function(getLocationRes) {
                                            // console.log(getLocationRes);
                                            //百度转换GPS坐标至百度坐标API
                                            var transformPosUrl = "http://api.map.baidu.com/geoconv/v1/?coords=" + getLocationRes.longitude + "," + getLocationRes.latitude + "&callback=JSON_CALLBACK&from=1&to=5&ak=7vVOlMOKr03PaWX82WajF6mG";

                                            $http.jsonp(transformPosUrl)
                                                    .then(function(bdRes) {
                                                        // console.log( bdRes );
                                                        /**
                                                         * 根据算法判断是否在目标城市内
                                                         * 判断依据为指定坐标为圆心的30公里范围内
                                                         */
                                                        var isIn = checkUserPosition.getDistance($rootScope.cityLocation.lat, $rootScope.cityLocation.lng, bdRes.data.result[0].y, bdRes.data.result[0].x) < 30 ? true : false;

                                                        // alert("是否在城市范围内:" + isIn );

                                                        $rootScope.userLocation = {
                                                            latitude: isIn ? (bdRes.data.result[0].y).toString() : $rootScope.cityLocation.lat,
                                                            longitude: isIn ? (bdRes.data.result[0].x).toString() : $rootScope.cityLocation.lng
                                                        };
                                                        // console.log($rootScope.userLocation);
                                                        // 113.119092,22.56342
                                                        // $rootScope.userLocation = {
                                                        //     latitude : "36.571278218682",
                                                        //     longitude: "109.48809913015"
                                                        // };

                                                        if (!isIn && $rootScope.cityNotIn !== "viewed") {

                                                            var alertPopup = $ionicPopup.alert({
                                                                title: '提示',
                                                                template: '您所在的城市尚未开通 ' + $rootScope.systemName + ' 服务，系统将自动切换至' + $rootScope.cityName + '市',
                                                                okText: "我知道了",
                                                                okType: "button-balanced"
                                                            });
                                                            alertPopup.then(function() {
                                                                localStorageService.set("cityNotIn", "viewed");
                                                            });

                                                        }
                                                        /*$rootScope.cityLocation = {
                                                         lat: "36.601492",
                                                         lng: "109.495103"
                                                         };*/
                                                        var lng = null;
                                                        var lat = null;
                                                        if (!isIn) {
                                                            lat = $rootScope.cityLocation.lat;
                                                            lng = $rootScope.cityLocation.lng;
                                                        } else {
                                                            lat = bdRes.data.result[0].y;
                                                            lng = bdRes.data.result[0].x;
                                                        }
                                                        // alert("纬度" + bdRes.data.result[0].y + ";" + "经度" + bdRes.data.result[0].x  );

                                                        var getCityfromePos = "http://api.map.baidu.com/geocoder/v2/?ak=7vVOlMOKr03PaWX82WajF6mG&location=" + lat + "," + lng + "&callback=JSON_CALLBACK&output=json";

                                                        $http.jsonp(getCityfromePos)
                                                                .then(function(cityPos) {
                                                                    // alert("当前详细地址:" + cityPos.data.result.formatted_address );

                                                                    $rootScope.userLocation.nowCity = cityPos.data.result.addressComponent.city;
                                                                    $rootScope.userLocation.nowAddress = cityPos.data.result.formatted_address;
                                                                    $rootScope.myAddress = {
                                                                        name: cityPos.data.result.formatted_address,
                                                                        location: {
                                                                            lat: lat,
                                                                            lng: lng
                                                                        }
                                                                    }
                                                                    localStorageService.set("myAddress", JSON.stringify($rootScope.myAddress));
                                                                    // console.log( $rootScope.userLocation );
                                                                    // alert( $rootScope.userLocation.nowAddress );

                                                                    //返回所有查询结束后的成功消息Promise
                                                                    //告诉后续代码前期工作已准备完毕
                                                                    $rootScope.appReadyPromise.resolve("finished");

                                                                }, function(error) {
                                                                    $rootScope.appReadyPromise.reject(error);
                                                                });


                                                    });

                                        }
                                    });

                                    /**
                                     * 微信中隐藏所有非基础类按钮
                                     */
                                    wx.hideAllNonBaseMenuItem();

                                    /**
                                     * 微信中批量显示指定按钮
                                     * @type {Array}
                                     */
                                    wx.showMenuItems({
                                        menuList: [
                                            "menuItem:share:appMessage", //分享给朋友
                                            "menuItem:share:timeline", //分享到朋友圈
                                            "menuItem:favorite" //收藏
                                        ]
                                    });

                                    wx.onMenuShareAppMessage({
                                        title: $rootScope.systemName, // 分享标题
                                        desc: '实时掌握附近站点与车辆预测到站信息', // 分享描述
                                        link: $rootScope.rootAbsoluteUrl, // 分享链接
                                        imgUrl: $rootScope.rootAbsoluteUrl + '/img/share-logo.png', // 分享图标
                                        success: function() {
                                            /*var sharePop = $ionicPopup.alert({
                                             title: '提示',
                                             template: '成功分享给朋友！',
                                             okText: "确定",
                                             okType: "button-balanced"
                                             });*/

                                        },
                                        cancel: function() {
                                            // 用户取消分享后执行的回调函数
                                        }
                                    });

                                    wx.onMenuShareTimeline({
                                        title: $rootScope.systemName, // 分享标题
                                        link: $rootScope.rootAbsoluteUrl, // 分享链接
                                        imgUrl: $rootScope.rootAbsoluteUrl + '/img/share-logo.png', // 分享图标
                                        success: function() {
                                            // 用户确认分享后执行的回调函数
                                            var sharePop = $ionicPopup.alert({
                                                title: '提示',
                                                template: '成功分享到朋友圈！',
                                                okText: "确定",
                                                okType: "button-balanced"
                                            });
                                        },
                                        cancel: function() {
                                            // 用户取消分享后执行的回调函数
                                        }
                                    });

                                });

                                wx.error(function(error) {
                                    console.warn(error);
                                    alert("微信服务获取出错，请与管理员联系.");
                                });

                                //移除数据表
                                // weAppDataBase.dropDB();

                                /**
                                 * 使用WebSQL创建一个stations database
                                 */
                                weAppDataBase.createDB();


                                // weAppDataBase.deleteDB().then(function(res){
                                //   localStorageService.set("initStationLineDb", null);
                                // });

                                /**
                                 * 如果没有插入原始数据，则请求服务器后将原始数据插入WebSQL中。使用LocalStorage进行标识
                                 * @param  {[type]} localStorageService.get("initStationLineDb") !             [description]
                                 * @return {[type]}                                              [description]
                                 */

                                if (localStorageService.get("initStationLineDb") !== "created") {
                                    $ionicLoading.show({
                                        template: '正在初始化数据...'
                                    });
                                    var req = {
                                        method: 'post',
                                        url: $rootScope.rootLocation + '/line/station/update',
                                        data: {
                                            "cityCode": $rootScope.cityCode,
                                            "cityName": $rootScope.cityName
                                        }
                                    };

                                    $http(req)
                                            .then(function(result) {
                                                $ionicLoading.show({
                                                    template: '开始插入数据...'
                                                });
                                                var stations = result.data.data.lineStations;

                                                if (stations.length) {
                                                    for (var i = 0; i < stations.length; i++) {
                                                        var thisStation = stations[i];
                                                        weAppDataBase.insert(thisStation.lineId, thisStation.lineName, thisStation.cityMapCode, thisStation.cityName);
                                                    }
                                                    localStorageService.set("initStationLineDb", "created");
                                                }
                                                ;
                                                $ionicLoading.hide();
                                            })

                                }


                            });

                    return $rootScope.appReadyPromise.promise;

                    // $ionicPlatform.ready(function() {
                    //   // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
                    //   // for form inputs)
                    //   if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
                    //     cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
                    //     cordova.plugins.Keyboard.disableScroll(true);

                    //   }
                    //   if (window.StatusBar) {
                    //     // org.apache.cordova.statusbar required
                    //     StatusBar.styleDefault();
                    //   }
                    // });

                }])

            .config(['$ionicConfigProvider', '$stateProvider', '$urlRouterProvider', 'localStorageServiceProvider', '$httpProvider',
                function($ionicConfigProvider, $stateProvider, $urlRouterProvider, localStorageServiceProvider, $httpProvider) {

                    // if(!ionic.Platform.isIOS()) $ionicConfigProvider.scrolling.jsScrolling(false);

                    localStorageServiceProvider.setPrefix('zhxWeApp');

                    $httpProvider.interceptors.push('requestInerceptor');

                    $stateProvider

                            .state('index', {
                                url: '/index',
                                templateUrl: 'templates/tab-dash.html',
                                controller: 'DashCtrl',
                                cache: false
                            })
                            .state('search', {
                                url: '/search',
                                templateUrl: 'templates/search.html',
                                controller: 'searchCtrl',
                                cache: false
                            })
                            .state('searchRes', {
                                url: '/search-result/',
                                templateUrl: 'templates/search-result.html',
                                controller: 'searchResCtrl',
                                cache: false,
                                params: {
                                    searchText: null
                                }
                            })
                            .state('station', {
                                url: '/station',
                                templateUrl: 'templates/station.html',
                                controller: 'stationCtrl',
                                cache: false
                            })
                            .state('line', {
                                url: '/line',
                                templateUrl: 'templates/line.html',
                                controller: 'lineCtrl',
                                cache: false,
                                params: {
                                    searchText: null
                                }
                            })
                            .state('favor', {
                                url: '/favor',
                                templateUrl: "templates/favor.html",
                                controller: "favorCtrl",
                                cache: false
                            })
                            .state('trans', {
                                url: '/trans',
                                templateUrl: "templates/trans.html",
                                controller: "transCtrl",
                                cache: false,
                                params: {
                                    data: null
                                }
                            })
                            .state('location', {
                                url: '/location',
                                templateUrl: "templates/location.html",
                                controller: "locationCtrl",
                                cache: false,
                                params: {
                                    tit: null,
                                    tag: null
                                }
                            })
                            .state('map', {
                                url: '/map',
                                templateUrl: "templates/map.html",
                                controller: "mapCtrl",
                                cache: false,
                                params: {
                                    tit: null,
                                    tag: null
                                }
                            })
                            .state('transfer', {
                                url: '/transfer',
                                templateUrl: "templates/transfer.html",
                                controller: "transferCtrl",
                                cache: false,
                                params: {
                                    data: null
                                }
                            })
                            .state('more', {
                                url: '/more',
                                templateUrl: "templates/more.html",
                                cache: false
                            })
                            .state('assess', {
                                url: '/assess',
                                templateUrl: "templates/assess.html",
                                controller: "assessCtrl",
                                cache: false
                            })
                            .state('about', {
                                url: '/about',
                                templateUrl: "templates/about.html",
                                cache: false
                            })
                            .state('help', {
                                url: '/help',
                                templateUrl: "templates/help.html",
                                controller: "helpCtrl",
                                cache: false
                            })
                            .state('question', {
                                url: '/question',
                                templateUrl: "templates/question.html",
                                controller: "questionCtrl",
                                cache: false
                            })
                            .state('board', {
                                url: '/board',
                                templateUrl: "templates/board.html",
                                controller: "boardCtrl",
                                cache: false
                            })
                            .state('helpContent', {
                                url: '/helpContent',
                                templateUrl: "templates/helpContent.html",
                                controller: "helpContentCtrl",
                                cache: false
                            })
                            .state('boardContent', {
                                url: '/boardContent',
                                templateUrl: "templates/boardContent.html",
                                controller: "boardContentCtrl",
                                cache: false
                            });


                    // if none of the above states are matched, use this as the fallback
                    $urlRouterProvider.otherwise('/trans');

                }]);

    // wx.ready(function(){
    //   wx.getLocation({
    //     type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
    //     success: function (res) {
    //       console.log( res );
    //         var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
    //         var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
    //         var speed = res.speed; // 速度，以米/每秒计
    //         var accuracy = res.accuracy; // 位置精度
    //     }
    //   })
    // });

    /**
     * common js
     * Designed by vicco
     * 2015-10-09
     */
    /**
     * JAVASCRIPT 全局数组对象新增 indexOf 和 remove 两个方法
     * 用来移除数组中指定值（非下标）
     */
    Array.prototype.indexOf = function(val) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == val)
                return i;
        }
        return -1;
    };
    Array.prototype.remove = function(val) {
        var index = this.indexOf(val);
        if (index > -1) {
            this.splice(index, 1);
        }
    };

    //去除字符串所有空格
    String.prototype.trimSpace = function() {
        return this.replace(/\s+/g, "");
    };

})();


(function() {
    'use strict';

    /**
     * 创建weApp 控制器
     */
    angular.module('weApp.controllers', [])

            /**
             *
             * 线路站点查询(首页面)
             * tab-dash.html
             *
             */
            .controller('DashCtrl', ['$scope', '$rootScope', '$http', '$timeout', '$state', 'localStorageService', '$ionicModal', '$ionicPopup', 'showLinePageService', 'myFavorsService', 'weAppDataBase', '$compile',
                function($scope, $rootScope, $http, $timeout, $state, localStorageService, $ionicModal, $ionicPopup, showLinePageService, myFavorsService, weAppDataBase, $compile) {
                    $rootScope.appReadyPromise.promise.then(function(res) {
                        if (res == "finished") {
                            //获取附近站点URL配置
                            var nearbyUrl = $rootScope.rootLocation + "/line/station/nearby";
                            //获取线路站点更新
                            var stationUpdateUrl = $rootScope.rootLocation + "/line/station/update";
                            //获取附近站点参数配置
                            var req = {
                                method: 'post',
                                url: nearbyUrl,
                                data: {
                                    "longitude": $rootScope.userLocation.longitude,
                                    "latitude": $rootScope.userLocation.latitude,
                                    "cityCode": $rootScope.cityCode,
                                    "cityName": $rootScope.cityName
                                }
                            };

                            //系统默认城市
                            $scope.systemNormalCity = $rootScope.cityName;
                            //系统默认名称
                            $scope.sysName = $rootScope.systemName;

                            //定位城市
                            $scope.nowCity = $rootScope.userLocation.nowCity;
                            /**
                             * zhx-pop-tip 状态
                             * @type {Boolean} set true to show, set false to hide
                             */
                            $scope.tipShown = false;
                            /**
                             * Local Favors init
                             */
                            $scope.myFavors = $scope.myFavorsJSON = null;

                            //首页当前坐标周围的线路站点信息读取
                            $scope.doRefresh = function() {

                                // $http(req).then(function(result){
                                //   console.log(result);
                                // })

                                //首页当前坐标周围的线路站点信息读取
                                $http(req)
                                        .then(function(result) {

                                            /**
                                             * 附近站点原始数据
                                             * TODO 需要修改格式
                                             * @type {[type]}
                                             */
                                            $scope.lineStation = result.data.data.stations;

                                            //重构数据
                                            //这里根据上下行重构起止时间
                                            if ($scope.lineStation.length) {
                                                for (var i = 0, len = $scope.lineStation.length; i < len; i++) {
                                                    var stationLines = $scope.lineStation[i].lineStations;
                                                    if (stationLines.length) {
                                                        for (var j = 0, jLen = stationLines.length; j < jLen; j++) {
                                                            var line = stationLines[j];
                                                            //默认值为上行
                                                            line.evalStartBusTime = line.firstBusTime;
                                                            line.evalEndBusTime = line.lastBusTime;
                                                            //下行替换
                                                            if (line.lineType === 2) {
                                                                if (angular.isUndefined(line.downFirstBusTime) || angular.isUndefined(line.downLastBusTime)) {
                                                                    line.evalStartBusTime = line.firstBusTime;
                                                                    line.evalEndBusTime = line.lastBusTime;
                                                                } else {
                                                                    line.evalStartBusTime = line.downFirstBusTime.trimSpace() == "" ? line.firstBusTime : line.downFirstBusTime;
                                                                    line.evalEndBusTime = line.downLastBusTime.trimSpace() == "" ? line.lastBusTime : line.downLastBusTime;
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }

                                            /**
                                             * 是否存在用户收藏的线路
                                             * $scope.myFavors [Array] 收藏 数组 <ID>
                                             * $scope.myFavorsJSON [JSON Array] 收藏 数组 <JSON data>
                                             * 这里需要将两个属性< myFavors > < myFavorsJSON > 初始化完毕
                                             */
                                            if (localStorageService.get("myFavors") !== null && localStorageService.get("myFavorsJSON") !== null) {
                                                $scope.myFavors = JSON.parse(localStorageService.get("myFavors"));
                                                $scope.myFavorsJSON = JSON.parse(localStorageService.get("myFavorsJSON"));
                                            } else {
                                                //如果没有任何收藏数据，则直接存入浏览器空数据
                                                localStorageService.set("myFavors", null);
                                                localStorageService.set("myFavorsJSON", null);
                                            }

                                            $scope.$broadcast('scroll.refreshComplete');

                                        });

                            }

                            $scope.doRefresh();

                            /**
                             * 页面每次进入时读取一下本地收藏
                             * @param  {[type]} event [description]
                             * @param  {[type]} data  ){                      $scope.myFavors [description]
                             * @return {[type]}       [description]
                             */
                            $scope.$on("$ionicView.beforeEnter", function(event, data) {
                                $scope.myFavors = localStorageService.get("myFavors") == null ? [] : JSON.parse(localStorageService.get("myFavors"));
                                $scope.myFavorsJSON = localStorageService.get("myFavorsJSON") == null ? [] : JSON.parse(localStorageService.get("myFavorsJSON"));
                            });

                            /**
                             * 打开附近某个站点下面所有线路列表的页面
                             * @param  {[type]} station      [JSON Object]
                             * @param  {[type]} stationIndex [ngRepeat Index]
                             */
                            $scope.showStationLinePage = function(station, stationIndex) {
                                //循环出的第一个站点因为设计为展开状态，因此不需要使用该方法显示其下面的线路
                                if (!stationIndex)
                                    return;

                                //将当前点击的线路名称存入浏览器
                                sessionStorage.setItem("nowStationName", station.stationName);

                                /**
                                 * 点击某个站点后，通过该站点的ID将其下面所有线路的JSON数据从原始数据中过滤出来，并存入sessionStorage，供后面的子页面使用
                                 */
                                for (var i = 0; i < $scope.lineStation.length; i++) {
                                    // if( $scope.lineStation[i].stationId == station.stationId ){
                                    // 目前接收到的数据已无  $scope.lineStation[i].stationId 这个属性字段，只能用stationName来判断
                                    if ($scope.lineStation[i].stationName == station.stationName) {
                                        sessionStorage.setItem("clickStation", JSON.stringify($scope.lineStation[i].lineStations));
                                        break;
                                    }
                                }
                                //最后通过ui-router跳转页面
                                $state.go("station");

                            };

                            /**
                             * 打开线路详细页面（直线图页面）点击事件
                             * @param  {[type]} line  [线路JSON Data]
                             * @param  {[type]} event [当前点击的 event 对象]
                             */
                            $scope.showLine = function(line, event) {
                                if (angular.element(event.target).hasClass('station-favor') || angular.element(event.target).hasClass('we-font'))
                                    return;
                                showLinePageService.gotoLinePage(line, event);
                            };

                            /**
                             * 点击后将该线路加入本地收藏
                             * 收藏的数据将会被存入本地浏览器的LocalStorage中
                             * @param  {[type]} line  [line JSON Data]
                             * @param  {[type]} event [click event]
                             */
                            $scope.favorLine = function(line, event) {
                                //当前点击的lineID;
                                var stationId = line.lineStationId;
                                //如果当前myFavors数组总不含有当前点击的lineID
                                //意为当前点击的线路并未被收藏则执行收藏操作
                                if ($scope.myFavors == null)
                                    $scope.myFavors = [];
                                if ($scope.myFavors.indexOf(stationId) == -1) {
                                    //通过服务存入LocalStorage
                                    myFavorsService.set(line);
                                    //存入当前页面临时数组中
                                    $scope.myFavors.push(stationId);
                                    $scope.tipShown = true;
                                    $scope.tipContent = '收藏成功';

                                } else {    //移除操作
                                    //通过服务移除LocalStorage中的当前线路
                                    myFavorsService.remove(line);
                                    //移除临时数组中的ID
                                    $scope.myFavors.remove(stationId);
                                    $scope.tipShown = true;
                                    $scope.tipContent = '取消收藏成功';
                                }

                            }


                            //城市选择页面（modal）
                            $ionicModal.fromTemplateUrl("templates/city.html", {
                                scope: $scope,
                                animation: 'slide-in-up'
                            })
                                    //打开成功后回调
                                    .then(function(modal) {

                                        $scope.cityModal = modal;

                                        //选择城市事件
                                        $scope.selectCity = function(city) {

                                            $ionicPopup.confirm({
                                                title: "选择城市",
                                                template: "将城市切换至<strong>" + city + "</strong>？",
                                                cancelText: "取消",
                                                okText: "确定",
                                                okType: "button-balanced"
                                            }).then(function(res) {
                                                if (res) {
                                                    console.log("clear all histroy!");
                                                    $scope.cityModal.hide()
                                                } else {
                                                    console.log("clear all histroy has been canceled!");
                                                }
                                            })

                                        }

                                    });


                            //modal关闭后垃圾回收
                            $scope.$on('$destroy', function() {
                                $scope.cityModal.remove();
                            });

                        }

                    })

                }])

})();

(function() {
    'use strict';

    angular.module("weApp.directives", [])

            .directive('myfocus', ['$timeout', function($timeout) {
                    return {
                        link: function(scope, element) {
                            $timeout(function() {
                                element[0].focus();
                            }, 300);
                        }
                    };
                }])

            .directive("zhxPageLoading", ['$compile', function($compile) {
                    return {
                        restrict: "E",
                        replace: true,
                        template: "<div id='zhx-page-loading'></div>",
                        link: function(scope, element) {
                            var spinner = $compile("<ion-spinner icon='android'></ion-spinner>")(scope);
                            element.append(spinner);
                        }
                    }
                }])

            .directive("zhxPopTip", ['$timeout', function($timeout) {
                    return {
                        restrict: "E",
                        replace: true,
                        scope: {
                            showTip: '=',
                            content: '=',
                            time: '='
                        },
                        link: function(scope, element, attrs) {

                            scope.$watch('showTip', function(nv, ov) {
                                if (nv) {
                                    $timeout(function() {
                                        scope.showTip = !scope.showTip;
                                    }, scope.time || 1200);
                                }
                            });

                        },
                        template: '<div class="zhx-pop-tip-container" ng-class="{ zhxPopTipActive : showTip }">' +
                                '<div class="zhx-pop-tip">' +
                                '<div class="zhx-pop-content">{{ content }}</div>' +
                                '</div>' +
                                '</div>'

                    }
                }])

            .directive("lineMap", ['$rootScope', '$state', '$timeout', '$http', '$ionicLoading', function($rootScope, $state, $timeout, $http, $ionicLoading) {
                    return {
                        restrict: "E",
                        scope: {
                            lineData: '=',
                            favors: '=',
                            getLineData: '&'
                        },
                        replace: true,
                        template: "<div id='line-map' ng-style='{ width: stationLineWidth , height: stationLineHeight, background: stationLineColor }'>" +
                                //循环所有车辆实时位置
                                "<div class='we-font we-icon-bus1 line-map-bus' " +
                                " ng-repeat='bus in lineBus track by bus.busNum' " +
                                " ng-if='!busLeftArr[$index].repeat' " +
                                " ng-style='{ left: busLeftArr[$index].busPos }' " +
                                " ng-class='{ nearByBus : nearbyBusNum == bus.busNum && !noBus }'>" +
                                // "<label class='bus-num' ng-if='nearbyBusNum == bus.busNum && !noBus'>{{nearbyBusNum}}</label>" +
                                "<div class='topbusNum' ng-if='nearbyBusNum == bus.busNum && !noBus'>{{ bus.busNum }}</div>" +
                                "<span ng-if='busLeftArr[$index].repeatNum > 0' ng-class='{ nearByBusTip: busLeftArr[$index].repeatBusNum.indexOf( nearbyBusNum ) >= 0 }'>{{ busLeftArr[$index].repeatNum + 1 }}</span>" +
                                "</div>" +
                                //循环出直线图站点圆点
                                "<div class='line-map-station-dot' " +
                                " ng-style='{ left : $index * stationDistance + 25, width: stationLineHeight - 2, height: stationLineHeight - 2 }' " +
                                " ng-repeat='s in lineData track by s.lineStationId'></div>" +
                                //当前站点位置标记
                                "<div ng-if='isNowStation' class='line-map-pos' ng-style='{left : nowStationLeft }'></div>" +
                                // 循环出直线图所有站点名称
                                "<div bindonce class='line-map-station' " +
                                " ng-style='{ left : $index * stationDistance + 18, height: maxTextLen * 19.5 + 40 }' " +
                                " ng-repeat='s in lineData track by s.lineStationId' ng-click='showStationPrec({{s}})'> " +
                                " <span ng-if='favors.indexOf( s.lineStationId ) == -1' bo-text='$index + 1'></span> " +
                                " <span ng-if='favors.indexOf( s.lineStationId ) != -1' class='we-font we-icon-favorfill favor-active'></span>" +
                                " <span class='station-name' ng-class='{ nowStation: isNowStation == s.lineStationId }' ng-style='{ fontSize : s.autoSmallFont }' bo-text='s.stationName'></span>" +
                                "</div>" +
                                "</div>",
                        controller: ["$scope", "$ionicScrollDelegate", "localStorageService", function($scope, $ionicScrollDelegate, localStorageService) {

                                //直线图上点击任意站点查询预测时间
                                $scope.showStationPrec = function(station) {
                                    //防止多次点击重复获取数据
                                    if ($scope.isNowStation != station.lineStationId) {

                                        /**
                                         * 每当切换站点都应该更新session中的当前限流站点信息，保证收藏站点的正确
                                         */
                                        sessionStorage.setItem("clickLine", JSON.stringify(station));
                                        $scope.getLineData();

                                        $scope.clickStationName = station.stationName;
                                        $scope.isNowStation = station.lineStationId;
                                        $scope.nowStationLeft = (parseInt(station.seq) - 1) * $scope.stationDistance + 21;
                                        $scope.nowStationObj = station;
                                        $scope.searchNearbyBus(station);
                                    }
                                };

                                //画面滚动至当前站点
                                $scope.scrollTo = function(leftPos) {
                                    $ionicScrollDelegate.$getByHandle("lineMap").scrollTo(leftPos, 0, true);
                                }

                            }],
                        link: function(scope, element, attrs) {

                            //监测线路基础数据读取情况
                            scope.lineDataWatcher = scope.$watch('lineData', function(nv, ov) {
                                if (nv !== ov && nv.length) {
                                    //延迟事件是为了保证更多低端机型在转场动画后再渲染直线图
                                    $timeout(function() {
                                        scope.initMap();
                                        // console.log("line107: 初始化直线图");
                                    }, 300);
                                }
                            });

                            //绘制直线图
                            scope.initMap = function() {

                                //当前线路所有的车的数组对象
                                scope.lineBus = [];
                                //该数组存入的为当前线路所有车辆在直线图中相对左侧的位置< 也就是车辆的实时位置 >
                                scope.busLeftArr = [];
                                scope.nowStationObj = null;
                                scope.noBus = false;

                                scope.isNowStation = null;

                                scope.isAutoRefresh = true;
                                scope.autoRefreshTime = 6000;

                                scope.busInterval = null;

                                //每站在页面上的间距（PX像素）
                                scope.stationDistance = 50;
                                //直线图高度
                                scope.stationLineHeight = 8;
                                //直线图背景色
                                scope.stationLineColor = "#0d9d57";
                                //直线图上一共多少站
                                scope.stationNum = scope.lineData.length;
                                //计算整体直线图需要的长度，长度根据线路多少和间距来确定
                                scope.stationLineWidth = scope.stationNum * scope.stationDistance;
                                //当前线路下最长站名一共几个字，根据这个来计算站名高度
                                scope.maxTextLen = 0;

                                var nowStationLine = JSON.parse(sessionStorage.getItem('clickLine'));

                                /**
                                 * 设置线路上的当前站点显示的临时方法
                                 */
                                var setNowStationPos = function() {
                                    //设置第几站为当前站
                                    scope.isNowStation = line.lineStationId;
                                    //设置当前站
                                    scope.nowStationObj = line;
                                    //页面打开时自动滚动到当前站点（距离屏幕四站）
                                    //位置刚好在中间偏右，方便查看离当前站点最近的几辆车
                                    scope.scrollTo((i - 4) * scope.stationDistance);
                                    scope.nowStationLeft = i * scope.stationDistance + 21;
                                };

                                var stationTextLenArr = [];

                                for (var i = 0; i < scope.lineData.length; i++) {
                                    var line = scope.lineData[i];

                                    stationTextLenArr.push(line.stationName.length);

                                    if (line.stationName.length > 10) {
                                        scope.lineData[i].autoSmallFont = '.95em';
                                    }

                                    /**
                                     * 设置线路上的当前站点显示
                                     * @param  {[type]} line.lineStationId [description]
                                     * @return {[type]}                    [description]
                                     */
                                    if (line.lineStationId == nowStationLine.lineStationId) {
                                        setNowStationPos();
                                    } else {
                                        /**
                                         * 如果用户使用了换向功能，目前无法通过独立ID来设置换向后的当前站点，只能以站点名称来判断。
                                         * @type {[type]}
                                         */
                                        if (line.stationName == nowStationLine.stationName) {
                                            setNowStationPos();
                                            /**
                                             * 每当切换站点都应该更新session中的当前限流站点信息，保证收藏站点的正确
                                             */
                                            sessionStorage.setItem("clickLine", JSON.stringify(line));
                                            scope.getLineData();

                                        }
                                    }
                                }

                                /**
                                 * 对所有站名长度进行排序
                                 */
                                stationTextLenArr.sort(scope.sortArr);
                                scope.maxTextLen = stationTextLenArr[0];

                                /**
                                 * 如果用户进入线路预测页面但没有查询到当前站点，则需要进行一些容错处理
                                 * @param  {[type]} scope.nowStationObj [description]
                                 * @return {[type]}                     [description]
                                 */
                                if (scope.nowStationObj == null) {
                                    for (var i = 0; i < scope.lineData.length; i++) {
                                        var line = scope.lineData[i];
                                        if (line.seq == nowStationLine.seq) {
                                            setNowStationPos();
                                            /**
                                             * 每当切换站点都应该更新session中的当前限流站点信息，保证收藏站点的正确
                                             */
                                            sessionStorage.setItem("clickLine", JSON.stringify(line));
                                            scope.getLineData();

                                        }
                                    }
                                }
                                if (scope.nowStationObj == null) {
                                    console.warn("line197: 该线路下没有找到对应站点.");
                                    //如果在该线路下获取不到对应站点，则将该线路第一站点设置为当前站点；
                                    scope.nowStationObj = scope.lineData[0];
                                    //并弹出提示
                                    scope.$parent.lineData.lineStationId = "zhx-no-bus";
                                    scope.$parent.lineData.tipShown = true;
                                    scope.$parent.lineData.tipContent = "没有找到定位的站点/相应序号.";
                                    scope.$parent.lineData.tipTime = 2000;
                                    scope.scrollTo(0);
                                    $ionicLoading.hide();
                                    // $state.go( $rootScope.prevState );
                                    // return;
                                }

                                //绘制线路上存在的公交实时位置
                                scope.initStationBus();

                            };

                            /**
                             * 目前接收控制器传来的事件，主要刷新车辆和单车预测信息
                             * @param  {[type]} event                            [description]
                             * @return {[type]}                                  [description]
                             */
                            scope.$on("refreshStationBus", function(event, data) {
                                scope.initStationBus();
                            });

                            //读取
                            scope.initStationBus = function() {
                                var nowLineData = JSON.parse(sessionStorage.getItem('clickLine'));

                                var req = {
                                    method: 'post',
                                    url: $rootScope.rootLocation + '/line/bus/positions',
                                    data: {
                                        "lineId": nowLineData.lineId,
                                        "lineType": nowLineData.lineType.toString(),
                                        "cityCode": $rootScope.cityCode
                                    }
                                };

                                $http(req)
                                        .then(function(result) {

                                            if (result.data.head.success == "true") {

                                                if (result.data.data.busInfos.length) {

                                                    // console.log(  result.data.data.busInfos );
                                                    //
                                                    scope.lineBus = result.data.data.busInfos;
                                                    $rootScope.busNums = result.data.data.busInfos;
                                                    var busPosArrTpl = [];

                                                    for (var i = 0; i < scope.lineBus.length; i++) {

                                                        var bus = scope.lineBus[i];

                                                        //计算每一个车辆在直线图上的实时位置
                                                        var busPos = (scope.stationDistance * parseFloat(bus.relativePosition)) + ((bus.seq - 1) * scope.stationDistance) + 18;


                                                        var req = {
                                                            busPos: busPos,
                                                            busNum: bus.busNum,
                                                            repeat: false,
                                                            repeatNum: 0,
                                                            repeatBusNum: []
                                                        }

                                                        busPosArrTpl.push(req);

                                                        /**
                                                         * 如果当前车辆与上一辆位置发生重叠，则将当前车辆隐藏，并设置上一辆车显示TIP，表示同一个图标下有几辆车重叠
                                                         */
                                                        //当然要从第二辆车开始循环
                                                        if (busPosArrTpl.length > 1) {
                                                            //如果当前车辆与上一辆车的位置距离 < 16像素，则因此当前车辆，设置上一辆车显示+1
                                                            if (busPos - busPosArrTpl[i - 1].busPos < 16) {
                                                                busPosArrTpl[i].repeat = true;
                                                                busPosArrTpl[i - 1].repeatBusNum.push(busPosArrTpl[i].busNum)
                                                                busPosArrTpl[i - 1].repeatNum += 1;
                                                            }
                                                        }

                                                    }
                                                    ;

                                                    /**
                                                     * 对临时数组进行倒序循环，累加所有重叠车辆。
                                                     */
                                                    for (var j = busPosArrTpl.length - 1; j >= 0; j--) {
                                                        var sbus = busPosArrTpl[j];
                                                        if (sbus.repeat) {
                                                            busPosArrTpl[j - 1].repeatNum += sbus.repeatNum;
                                                            busPosArrTpl[j - 1].repeatBusNum = $.merge(busPosArrTpl[j - 1].repeatBusNum, sbus.repeatBusNum);
                                                            sbus.repeatNum = 0;
                                                            sbus.repeatBusNum = [];
                                                        }
                                                    }

                                                    // console.log( busPosArrTpl );
                                                    //更新车辆实时位置
                                                    scope.busLeftArr = busPosArrTpl;
                                                    // console.log( scope.busLeftArr );
                                                    //
                                                    //查找最近一辆车
                                                    scope.searchNearbyBus(scope.nowStationObj);

                                                }


                                            } else {
                                                console.warn("line313: 获取车辆信息失败");
                                                scope.$parent.lineData.nobus = scope.noBus = true;
                                                $ionicLoading.hide();
                                            }


                                        }, function() {
                                            console.warn('line321: 获取车辆信息出错，请检查代码.');
                                            $ionicLoading.hide();
                                        })


                            };

                            /**
                             * 寻找距离当前站点最近的一辆车
                             * @param  {[type]} nowStationObject [description]
                             * @return {[type]}                  [description]
                             */
                            scope.searchNearbyBus = function(nowStationObject) {


                                var tplBusArr = [];

                                var filterArr = scope.filterObject('seq', scope.lineBus, parseInt(nowStationObject.seq) - 1);

                                //直接取临时数组中的最后一辆车就是最近的一辆
                                //因为车辆不论上下行，都是从左至右排列
                                var nearBus = filterArr.splice(filterArr.length - 1, 1);

                                if (!nearBus.length) {
                                    //这里需要设置无最近车辆的提示
                                    scope.$parent.lineData.nobus = scope.noBus = true;
                                    $ionicLoading.hide();
                                    return;
                                } else {
                                    scope.$parent.lineData.nobus = scope.noBus = false;
                                }

                                //循环后设置页面最近一辆车的样式
                                for (var j = 0; j < scope.lineBus.length; j++) {
                                    if (nearBus[0].busNum == scope.lineBus[j].busNum) {
                                        scope.nearbyBusNum = nearBus[0].busNum;
                                        // console.log( scope.nearbyBusNum );
                                        break;
                                    }

                                }
                                ;

                                //查询最近一辆车的实时预测数据
                                scope.loadNearByBusPrec(nearBus[0]);

                            };

                            /**
                             * 查询距离当前站点最近一辆车的实时数据
                             * @param  {[type]} nearByBus [description]
                             * @return {[type]}           [description]
                             */
                            scope.loadNearByBusPrec = function(nearByBus) {

                                /**
                                 * 请求数据的参数
                                 * @type {Object}
                                 */
                                var req = {
                                    method: 'post',
                                    url: $rootScope.rootLocation + '/line/bus/predict',
                                    data: {
                                        "lineId": scope.nowStationObj.lineId,
                                        "lineStationId": scope.nowStationObj.lineStationId,
                                        "busNum": nearByBus.busNum
                                    }
                                };

                                $http(req)
                                        .then(function(result) {

                                            if (result.data.head.success == "true") {
                                                scope.$parent.lineData.busInfo = result.data.data.busInfo;
                                                scope.$parent.lineData.busInfo.stationName = scope.clickStationName;
                                            } else {
                                                console.warn("line399: 获取最近一辆车预测信息失败");
                                            }

                                            $ionicLoading.hide();

                                        }, function() {
                                            console.warn('line407: 获取最近一辆车预测信息失败，请检查代码.');
                                            $ionicLoading.hide();
                                        })

                            };


                            // scope.sortArrObject = function(sortBy, list) {
                            // 	return list.sort(function(a, b) {
                            // 	    // 降序，若需要升序则互换两者位置
                            // 	    if( !$.isNumeric( a[sortBy] ) ){
                            // 	    	return parseFloat( b[sortBy] ) - parseFloat( a[sortBy] );
                            // 	    } else {
                            // 	    	return b[sortBy] - a[sortBy];
                            // 	    }
                            // 	});
                            // };
                            //
                            scope.sortArr = function(a, b) {
                                if (a < b) {
                                    return 1; // a排在b的后面
                                } else if (a > b) {
                                    return -1; // a排在b的前面
                                } else {
                                    return 0; // a 和 b 保持位置不变
                                }
                            }


                            /**
                             * 过滤出数组中的某个属性小于等于某值的数组对象
                             * 并返回符合条件的新数组对象
                             * @param  {[type]} prop [description]
                             * @param  {[type]} arr  [description]
                             * @param  {[type]} num  [description]
                             * @return {[type]}      [description]
                             */
                            scope.filterObject = function(prop, arr, num) {
                                var tplArr = [];
                                for (var i = 0; i < arr.length; i++) {
                                    if ($.isNumeric(arr[i][prop])) {
                                        var substract = num - arr[i][prop];
                                        if (substract >= 0)
                                            tplArr.push(arr[i]);
                                    } else {
                                        var substract = num - parseFloat(arr[i][prop]);
                                        if (substract >= 0)
                                            tplArr.push(arr[i]);
                                    }
                                }
                                return tplArr;
                            };

                        }

                    }
                }])

})();
(function() {
    'use strict';

    angular.module('weApp.controllers')

            //收藏页面
            .controller('favorCtrl', ['$scope', 'myFavorsService', 'showLinePageService', '$ionicPopup', '$rootScope',
                function($scope, myFavorsService, showLinePageService, $ionicPopup, $rootScope) {
                    $scope.lineStation = myFavorsService.getJson().reverse();

                    /**
                     * 打开线路详细页面（直线图页面）点击事件
                     * @param  {[type]} line  [线路JSON Data]
                     * @param  {[type]} event [当前点击的 event 对象]
                     */
                    $scope.showLine = function(line, event) {
                        if (angular.element(event.target).hasClass('station-favor') || angular.element(event.target).hasClass('we-font'))
                            return;
                        showLinePageService.gotoLinePage(line, event);
                    };

                    /**
                     * 下拉刷新
                     * @return {[type]} [description]
                     */
                    $scope.doRefresh = function() {
                        $scope.lineStation = myFavorsService.getJson();
                        $scope.$broadcast('scroll.refreshComplete');
                    };

                    /**
                     * 删除收藏线路
                     * @param  {[type]} line  [description]
                     * @param  {[type]} event [description]
                     * @return {[type]}       [description]
                     */
                    $scope.deleteFovor = function(line) {

                        var confirmPopup = $ionicPopup.confirm({
                            title: '取消收藏的线路',
                            cancelText: '取消',
                            okText: '确认',
                            okType: "button-balanced",
                            template: '取消收藏线路' + line.lineName + ' 吗?'
                        });
                        confirmPopup.then(function(res) {
                            if (res) {
                                myFavorsService.remove(line);
                                // $scope.lineStation = myFavorsService.getJson();
                                $scope.doRefresh();
                            }
                        });

                    };
                }])

})();

(function() {
    'use strict';

    angular.module('weApp.controllers')
            /**
             * 线路详情页面
             * @param  {[type]} $scope     [description]
             * @param  {[type]} $rootScope [description]
             * @param  {[type]} $state     [description]
             * @param  {[type]} $timeout   [description]
             * @param  {String}            [description]
             * @return {[type]}            [description]
             */
            .controller('lineCtrl', ['$scope', '$rootScope', '$state', '$stateParams', '$timeout', '$http', '$ionicLoading', 'localStorageService', 'myFavorsService', '$interval', '$ionicScrollDelegate', '$ionicGesture',
                function($scope, $rootScope, $state, $stateParams, $timeout, $http, $ionicLoading, localStorageService, myFavorsService, $interval, $ionicScrollDelegate, $ionicGesture) {


                    $scope.orientationchange = false;

                    if (!$rootScope.refreshPerSec)
                        $rootScope.refreshPerSec = 6250;

                    $scope.docHeight = document.documentElement.clientHeight;
                    $scope.autoHeight = $scope.docHeight - 260;
                    if ($scope.docHeight <= 480) {
                        $scope.scaleSmall = true;
                    }

                    //这里根据上下行重构起止时间
                    $scope.rebuildData = function(data) {
                        if (!angular.isObject(data))
                            return;
                        //默认值为上行
                        data.evalStartBusTime = data.firstBusTime;
                        data.evalEndBusTime = data.lastBusTime;
                        //下行替换
                        // if( data.lineType === 2 ){
                        //     data.evalStartBusTime = data.downFirstBusTime.trimSpace() == "" ? data.firstBusTime : data.downFirstBusTime;
                        //     data.evalEndBusTime = data.downLastBusTime.trimSpace() == "" ? data.lastBusTime : data.downLastBusTime;
                        // }
                        if (data.lineType === 2) {
                            if (angular.isUndefined(data.downFirstBusTime) || angular.isUndefined(data.downLastBusTime)) {
                                data.evalStartBusTime = data.firstBusTime;
                                data.evalEndBusTime = data.lastBusTime;
                            } else {
                                data.evalStartBusTime = data.downFirstBusTime.trimSpace() == "" ? data.firstBusTime : data.downFirstBusTime;
                                data.evalEndBusTime = data.downLastBusTime.trimSpace() == "" ? data.lastBusTime : data.downLastBusTime;
                            }
                        }
                    };

                    /**
                     * Local Favors init
                     */
                    $scope.myFavors = $scope.myFavorsJSON = null;

                    if (sessionStorage.getItem('clickLine') && sessionStorage.getItem('clickLine') != '') {
                        $scope.lineData = JSON.parse(sessionStorage.getItem('clickLine'));
                        $scope.rebuildData($scope.lineData);
                        $scope.stationName = sessionStorage.getItem('nowLineName');
                        $rootScope.lineData = $scope.lineData;
                    } else {
                        $state.go('index');
                    }

                    /**
                     * 供直线图指令调取的方法
                     * 更新lineData;
                     * @return {[type]} [description]
                     */
                    $scope.getLineDataFromMap = function() {
                        $scope.lineData = JSON.parse(sessionStorage.getItem('clickLine'));
                        $scope.rebuildData($scope.lineData);
                    }

                    /**
                     * 是否存在用户收藏的线路
                     * $scope.myFavors [Array] 收藏 数组 <ID>
                     * $scope.myFavorsJSON [JSON Array] 收藏 数组 <JSON data>
                     * 这里需要将两个属性< myFavors > < myFavorsJSON > 初始化完毕
                     */
                    if (localStorageService.get("myFavors") !== null && localStorageService.get("myFavorsJSON") !== null) {
                        $scope.myFavors = JSON.parse(localStorageService.get("myFavors"));
                        $scope.myFavorsJSON = JSON.parse(localStorageService.get("myFavorsJSON"));
                    } else {
                        //如果没有任何收藏数据，则直接存入浏览器空数据
                        localStorageService.set("myFavors", null);
                        localStorageService.set("myFavorsJSON", null);
                        $scope.myFavors = [];
                        $scope.myFavorsJSON = [];
                    }

                    /**
                     * 页面每次进入时读取一下本地收藏
                     * @param  {[type]} event [description]
                     * @param  {[type]} data  ){                      $scope.myFavors [description]
                     * @return {[type]}       [description]
                     */
                    $scope.$on("$ionicView.beforeEnter", function(event, data) {
                        $scope.myFavors = localStorageService.get("myFavors") == null ? [] : JSON.parse(localStorageService.get("myFavors"));
                        $scope.myFavorsJSON = localStorageService.get("myFavorsJSON") == null ? [] : JSON.parse(localStorageService.get("myFavorsJSON"));
                    });
                    // console.log( $rootScope.prevState.name )
                    //根据上一级菜单设置当前返回按钮的提示
                    switch ($rootScope.prevState.name) {
                        case 'index' :
                            $scope.prevPage = '首页';
                            break;
                        case 'station' :
                            $scope.prevPage = '站点';
                            break;
                        case 'favor' :
                            $scope.prevPage = '我的收藏';
                            break;
                        case 'searchRes' :
                            $scope.prevPage = '搜索结果';
                            break;
                        case 'transfer' :
                            $scope.prevPage = '线路换乘';
                            break;
                        case 'more' :
                            $scope.prevPage = '更多';
                            break;
                        case 'line' :
                            $scope.prevPage = '线路';
                            break;
                        default:
                            $scope.prevPage = '首页';
                            break;
                    }
                    ;

                    $scope.backToIndex = function() {

                        if ($rootScope.prevState.name) {
                            $state.go($rootScope.prevState, {searchText: $stateParams.searchText});
                        } else {
                            $state.go('index');
                        }

                    };
                    var req = {
                        method: 'post',
                        url: $rootScope.rootLocation + '/line/station/infos'
                        ,
                        data: {
                            "lineId": $scope.lineData.lineId,
                            "lineType": $scope.lineData.lineType.toString()
                        }
                    };

                    /**
                     * 换向
                     * @return {[type]} [description]
                     */
                    $scope.changeDirection = function() {
                        $ionicLoading.show({
                            template: '读取中...'
                        })
                        //获取当前起止站名
                        var startStation = $scope.lineData.firstStationName;
                        var endtStation = $scope.lineData.lastStationName;


                        //这里的switch是用来测试换向功能，届时数据接入后应直接根据获取的数据来判断
                        switch ($scope.lineData.lineType) {
                            case 1 :
                                req.data.lineType = "2";
                                $interval.cancel($scope.busInterval);
                                $http(req)
                                        .then(function(result) {
                                            if (result.data.head.success == "true") {
                                                $scope.linePreData = result.data.data.lineStations;
                                                $scope.lineData.lineType = 2;
                                                $scope.rebuildData($scope.lineData);
                                                sessionStorage.setItem("clickLine", JSON.stringify($scope.lineData));
                                                $scope.busInterval = $interval(function() {
                                                    $scope.refreshLineMap();
                                                }, $rootScope.refreshPerSec);
                                            } else {
                                                $scope.lineData.tipShown = true;
                                                $scope.lineData.tipContent = "没有找到换向的线路或者该线路为环线.";
                                                $scope.lineData.tipTime = 3000;
                                                $ionicLoading.hide();
                                            }

                                        });
                                break;
                            case 2 :
                                req.data.lineType = "1";
                                $interval.cancel($scope.busInterval);
                                $http(req)
                                        .then(function(result) {
                                            if (result.data.head.success == "true") {
                                                $scope.linePreData = result.data.data.lineStations;
                                                $scope.lineData.lineType = 1;
                                                $scope.rebuildData($scope.lineData);
                                                sessionStorage.setItem("clickLine", JSON.stringify($scope.lineData));
                                                $scope.busInterval = $interval(function() {
                                                    $scope.refreshLineMap();
                                                }, $rootScope.refreshPerSec);
                                            } else {
                                                $scope.lineData.tipShown = true;
                                                $scope.lineData.tipContent = "没有找到换向的线路或者该线路为环线.";
                                                $scope.lineData.tipTime = 3000;
                                                $ionicLoading.hide();
                                            }
                                        });
                                break;
                        }
                        //调换起止站名
                        $scope.lineData.firstStationName = endtStation;
                        $scope.lineData.lastStationName = startStation;

                    }

                    /**
                     * 刷新
                     * @return {[type]} [description]
                     */
                    $scope.refreshLineMap = function() {
                        $scope.$broadcast("refreshStationBus");
                    };

                    $scope.refreshLineMap2 = function() {
                        location.reload();
                    };

                    /**
                     * 评价
                     * @return {[type]} [description]
                     */
                    $scope.assessBus = function() {
                        console.log('assessBus');
                    };

                    $scope.busInterval = $interval(function() {
                        $scope.refreshLineMap();
                    }, $rootScope.refreshPerSec);

                    $scope.$on("$ionicView.beforeLeave", function() {
                        $interval.cancel($scope.busInterval);
                        console.log("定时刷新被移除了.");
                        //在离开前移除遮罩，如果在该页面加载出问题时，可以保证页面专场后不会被错误的遮罩。
                        $ionicLoading.hide();
                    });

                    /**
                     * 点击后将该线路加入本地收藏
                     * 收藏的数据将会被存入本地浏览器的LocalStorage中
                     * @param  {[type]} line  [line JSON Data]
                     * @param  {[type]} event [click event]
                     */
                    $scope.favorLine = function(event) {
                        //线路收藏时可能会因为用户点击任意站点而切换，所以每次需要重新获取line
                        var line = $scope.lineData;
                        //当前点击的lineID;
                        var stationId = line.lineStationId;
                        //如果当前myFavors数组总不含有当前点击的lineID
                        //意为当前点击的线路并未被收藏则执行收藏操作
                        if ($scope.myFavors.indexOf(stationId) == -1) {
                            //通过服务存入LocalStorage
                            myFavorsService.set(line);
                            //存入当前页面临时数组中
                            $scope.myFavors.push(stationId);
                            $scope.lineData.tipShown = true;
                            $scope.lineData.tipContent = '收藏成功';

                        } else {    //移除操作
                            //通过服务移除LocalStorage中的当前线路
                            myFavorsService.remove(line);
                            //移除临时数组中的ID
                            $scope.myFavors.remove(stationId);
                            $scope.lineData.tipShown = true;
                            $scope.lineData.tipContent = '取消收藏成功';
                        }
                        $scope.$broadcast("lineFavosChanged");

                    }

                    /**
                     * 获取当前线路站点信息
                     */
                    $ionicLoading.show({
                        template: '读取中...'
                    }).then(function() {
                        $http(req)
                                .then(function(result) {
                                    if (result.data.head.success == "true") {
                                        $scope.linePreData = result.data.data.lineStations;
                                    } else {
                                        $ionicLoading.hide();
                                        alert("获取当前站点线路出错，请重试，谢谢！");
                                        $state.go("index");
                                        return;
                                    }

                                });
                    });


                    $scope.dragDown = function(event) {
                        var mapTop = $ionicScrollDelegate.$getByHandle("lineMapContent").getScrollPosition().top;
                        if (mapTop > 0) {
                            $ionicScrollDelegate.$getByHandle("lineMapContent").scrollTo(0, mapTop - event.gesture.distance, true);
                        }
                    };

                    $scope.dragUp = function(event) {
                        var mapTop = $ionicScrollDelegate.$getByHandle("lineMapContent").getScrollPosition().top;
                        if (mapTop > 0) {
                            $ionicScrollDelegate.$getByHandle("lineMapContent").scrollTo(0, mapTop + event.gesture.distance, true);
                        }
                    }


                    window.addEventListener("orientationchange", function() {

                        if (window.orientation == -90 || window.orientation == 90) {

                            $ionicGesture.on("dragdown", $scope.dragDown, angular.element("#line-map-scroll"));

                            $ionicGesture.on("dragup", $scope.dragUp, angular.element("#line-map-scroll"));

                        } else {

                            $ionicGesture.off("dragdown", $scope.dragDown, angular.element("#line-map-scroll"));
                            $ionicGesture.off("dragup", $scope.dragUp, angular.element("#line-map-scroll"));

                            $ionicScrollDelegate.$getByHandle("lineMapContent").scrollTo(0, 0, true);

                        }

                    }, false);

                }])

})();

(function() {
    'use strict';

    angular.module('weApp.controllers')

            /**
             * 查询页面
             * @param  {[type]} $scope              [description]
             * @param  {[type]} $rootScope          [description]
             * @param  {[type]} $state              [description]
             * @param  {[type]} $timeout            [description]
             * @param  {[type]} $http               [description]
             * @param  {[type]} weAppDataBase       [description]
             * @param  {[type]} $ionicPopup         [description]
             * @param  {[type]} $compile            [description]
             * @param  {[type]} showLinePageService [description]
             * @return {[type]}                     [description]
             */
            .controller('searchCtrl', ['$scope', '$rootScope', '$state', '$stateParams', '$timeout', '$http', 'weAppDataBase', '$ionicPopup', '$compile', 'showLinePageService', 'localStorageService',
                function($scope, $rootScope, $state, $stateParams, $timeout, $http, weAppDataBase, $ionicPopup, $compile, showLinePageService, localStorageService) {


                    //设置一个键入延迟
                    var keyUpTimeout = null;

                    //查询历史
                    //TODO
                    $scope.searchContext = {
                        keyUpToSearch: false,
                        searchText: ''
                    }


                    $scope.$on("$ionicView.beforeEnter", function(event, data) {

                        if (localStorageService.get("searchHistory") !== null) {
                            $scope.searchHistory = localStorageService.get("searchHistory") == null ? [] : JSON.parse(localStorageService.get("searchHistory")).reverse();
                        } else {
                            localStorageService.set("searchHistory", null);
                        }

                    });

                    /**
                     * 自动focus 搜索输入框
                     *  在移动版safari(iPhone)上不支持
                     */
                    $scope.$on("$ionicView.enter", function(event, data) {
                        setTimeout(function() {
                            $("#searchInput").focus();
                        }, 10)
                    })

                    /**
                     * 输入关键字查询
                     * @return {[type]} [description]
                     */
                    $scope.searchLine = function() {
                        if (keyUpTimeout)
                            $timeout.cancel(keyUpTimeout);
                        keyUpTimeout = $timeout(function() {
                            $scope.searchContext.keyUpToSearch = true;
                            $scope.keyupResult = [];
                            if ($scope.searchContext.searchText != "") {
                                weAppDataBase.query($rootScope.cityCode, $scope.searchContext.searchText)
                                        .then(function(result) {
                                            angular.element("#keyup-search-list").empty();
                                            if (result.length) {
                                                for (var i = 0; i < result.length; i++) {
                                                    /**
                                                     * 这里取WebSQL回传的值必须已 rows.item(i) 的方式进行读取！
                                                     * 如果已 rows[i] 的方式读取，在chrome(Android)下正常，但在safari(iPhone)下则会报错！
                                                     * @type {[type]}
                                                     */
                                                    var me = result.item(i);
                                                    var stringMe = JSON.stringify(result.item(i));
                                                    //不能输出空字符
                                                    if ($.trim(stringMe) != "") {
                                                        var li = $compile("<li ng-click='showSearchResult(" + stringMe + ",$event);'>" + me.lineName + "</li>")($scope);
                                                        li.appendTo("#keyup-search-list");
                                                    }
                                                }
                                            } else {
                                                var li = angular.element("<li class='gray'>未查询到该线路或站点</li>");
                                                li.appendTo("#keyup-search-list");
                                            }
                                        });
                            } else {
                                angular.element("#keyup-search-list").empty();
                                $scope.keyupResult = [];
                            }
                        }, 300);

                    }

                    /**
                     * 打开线路详细页面（直线图页面）点击事件
                     * @param  {[type]} line  [线路JSON Data]
                     * @param  {[type]} event [当前点击的 event 对象]
                     */
                    $scope.clickSearch = function() {
                        var txt = $scope.searchContext.searchText;
                        if (txt) {
                            $state.go('searchRes', {searchText: txt});
                        }
                    };
                    $scope.showSearchResult = function(line, event) {
                        sessionStorage.setItem("nowLineName", line.lineName);
                        sessionStorage.setItem("clickLine", JSON.stringify(line));
                        $state.go('searchRes', {searchText: line.lineName});
                    };

                    $scope.searchHistoryLine = function(lineName) {
                        sessionStorage.setItem("nowLineName", lineName);
                        sessionStorage.setItem("clickLine", null);
                        $state.go('searchRes', {searchText: lineName});
                    }

                    $scope.clearSearchText = function() {
                        $scope.searchContext.searchText = null;
                        $scope.searchContext.keyUpToSearch = false;
                    }

                    //清空查询历史事件
                    $scope.delSearchConfirm = function() {
                        $ionicPopup.confirm({
                            title: "清空搜索记录",
                            template: "确认清空全部搜索记录吗？",
                            cancelText: "取消",
                            okText: "确定",
                            okType: "button-balanced"
                        }).then(function(res) {
                            if (res) {
                                localStorageService.set("searchHistory", null);
                                $state.reload();
                                console.log("clear all histroy!");
                            } else {
                                console.log("clear all histroy has been canceled!");
                            }
                        })
                    }


                }])

})();

(function() {
    'use strict';

    angular.module('weApp.controllers')

            /**
             * 查询结果展示页面
             * @param  {[type]} $scope                 [description]
             * @param  {[type]} $rootScope             [description]
             * @param  {[type]} $state                 [description]
             * @param  {[type]} $timeout               [description]
             * @param  {[type]} $http                  [description]
             * @param  {[type]} weAppDataBase          [description]
             * @param  {[type]} $ionicPopup            [description]
             * @param  {[type]} $compile               [description]
             * @param  {[type]} showLinePageService){                                  }] [description]
             * @return {[type]}                        [description]
             */
            .controller('searchResCtrl', ['$scope', '$rootScope', '$state', '$stateParams', '$timeout', '$http', 'weAppDataBase', 'showLinePageService', 'localStorageService', 'myFavorsService',
                function($scope, $rootScope, $state, $stateParams, $timeout, $http, weAppDataBase, showLinePageService, localStorageService, myFavorsService) {
                    $scope.searchKeywords = $stateParams.searchText;
                    if ($scope.searchKeywords) {
                        localStorageService.set("searchKeywords", $scope.searchKeywords);
                    } else {
                        $scope.searchKeywords = localStorageService.get("searchKeywords");
                    }

                    // console.log( $scope.searchKeywords );

                    //站点线路查询URL
                    var searchUrl = $rootScope.rootLocation + "/line/station/search";

                    //获取附近站点参数配置
                    var req = {
                        method: 'post',
                        url: searchUrl,
                        data: {
                            "stationLineName": $scope.searchKeywords,
                            "cityCode": $rootScope.cityCode,
                            "cityName": $rootScope.cityName
                        }
                    };


                    $http(req)
                            .then(function(result) {

                                // console.log( result );

                                $scope.station = result.data.data;
                                $rootScope.stations = result.data.data.lineStations;
                                if ($scope.station == undefined)
                                    return;

                                if ($scope.station.lineStations.length) {

                                    //重构数据
                                    //这里根据上下行重构起止时间
                                    var stationLines = $scope.station.lineStations;
                                    for (var j = 0, jLen = stationLines.length; j < jLen; j++) {
                                        var line = stationLines[j];
                                        //默认值为上行
                                        line.evalStartBusTime = line.firstBusTime;
                                        line.evalEndBusTime = line.lastBusTime;
                                        //下行替换
                                        if (line.lineType === 2) {
                                            if (angular.isUndefined(line.downFirstBusTime) || angular.isUndefined(line.downLastBusTime)) {
                                                line.evalStartBusTime = line.firstBusTime;
                                                line.evalEndBusTime = line.lastBusTime;
                                            } else {
                                                line.evalStartBusTime = line.downFirstBusTime.trimSpace() == "" ? line.firstBusTime : line.downFirstBusTime;
                                                line.evalEndBusTime = line.downLastBusTime.trimSpace() == "" ? line.lastBusTime : line.downLastBusTime;
                                            }

                                        }
                                    }

                                    /**
                                     * 将真正可以查询到结果的用户搜索条件插入到 搜索历史中。
                                     * @type {[type]}
                                     */
                                    if ($.trim($scope.searchKeywords) != "") {
                                        $scope.searchHistory = localStorageService.get("searchHistory") == null ? [] : JSON.parse(localStorageService.get("searchHistory"));
                                        if ($scope.searchHistory.indexOf($scope.searchKeywords) == -1) {
                                            $scope.searchHistory.push($scope.searchKeywords);
                                            localStorageService.set("searchHistory", JSON.stringify($scope.searchHistory));
                                        }
                                    }


                                    if (localStorageService.get("myFavors") !== null && localStorageService.get("myFavorsJSON") !== null) {
                                        $scope.myFavors = localStorageService.get("myFavors") == null ? [] : JSON.parse(localStorageService.get("myFavors"));
                                        $scope.myFavorsJSON = localStorageService.get("myFavorsJSON") == null ? [] : JSON.parse(localStorageService.get("myFavorsJSON"));
                                    } else {
                                        //如果没有任何收藏数据，则直接存入浏览器空数据
                                        localStorageService.set("myFavors", null);
                                        localStorageService.set("myFavorsJSON", null);
                                    }

                                }

                            });

                    /**
                     * 页面每次进入时读取一下本地收藏
                     * @param  {[type]} event [description]
                     * @param  {[type]} data  ){                      $scope.myFavors [description]
                     * @return {[type]}       [description]
                     */
                    $scope.$on("$ionicView.beforeEnter", function(event, data) {
                        $scope.myFavors = localStorageService.get("myFavors") == null ? [] : JSON.parse(localStorageService.get("myFavors"));
                        $scope.myFavorsJSON = localStorageService.get("myFavorsJSON") == null ? [] : JSON.parse(localStorageService.get("myFavorsJSON"));
                    });


                    /**
                     * 点击后将该线路加入本地收藏
                     * 收藏的数据将会被存入本地浏览器的LocalStorage中
                     * @param  {[type]} line  [line JSON Data]
                     * @param  {[type]} event [click event]
                     */
                    $scope.favorLine = function(line, event) {
                        //当前点击的lineID;
                        var stationId = line.lineStationId;
                        //如果当前myFavors数组总不含有当前点击的lineID
                        //意为当前点击的线路并未被收藏则执行收藏操作
                        if ($scope.myFavors == null)
                            $scope.myFavors = [];
                        if ($scope.myFavors.indexOf(stationId) == -1) {
                            //通过服务存入LocalStorage
                            myFavorsService.set(line);
                            //存入当前页面临时数组中
                            $scope.myFavors.push(stationId);
                            $scope.tipShown = true;
                            $scope.tipContent = '收藏成功';

                        } else {    //移除操作
                            //通过服务移除LocalStorage中的当前线路
                            myFavorsService.remove(line);
                            //移除临时数组中的ID
                            $scope.myFavors.remove(stationId);
                            $scope.tipShown = true;
                            $scope.tipContent = '取消收藏成功';
                        }

                    }

                    $scope.showLine = function(line, event, params) {
                        if (angular.element(event.target).hasClass('station-favor') || angular.element(event.target).hasClass('we-font'))
                            return;
                        showLinePageService.gotoLinePage(line, event, {searchText: $scope.searchKeywords});
                    }

                    $scope.backToIndex = function() {
                        // console.log( $rootScope.prevState.name );
                        if ($rootScope.prevState.name) {
                            $state.go('search');
                        } else {
                            $state.go('index');
                        }

                    }


                }])

})();

(function() {
    'use strict';

    angular.module("weApp.services", [])

            .factory('requestInerceptor', ['$q', function($q) {
                    var interceptor = {
                        'request': function(config) {

                            if (config.method == "POST") {

                                // config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
                                config.headers['regionCode'] = '440700';
                                config.headers['manufacturer'] = 'sxyd';
                                config.headers['versionCode'] = '17';
                                config.headers['deviceId'] = 'wx' + Date.parse(new Date());
                                config.headers['osType'] = '3';
                                config.headers['bi_auth'] = 'bus_intelligence';
                                // config.headers = {
                                // 	'content-type' : "application/x-www-form-urlencoded"
                                // 	// ,'regionCode' : '610600'
                                // 	// ,'manufacturer' : 'sxyd'
                                // 	// 'deviceId' : "wexin01234567890",
                                // 	// 'osType' : "3",
                                // 	// 'bi_auth' : "bus_intelligence"
                                // }
                                // console.log( config )
                            }

                            return config || $q.when(config);
                        },
                        'requestError': function(rejection) {
                            return $q.reject(rejection);
                        },
                        'response': function(response) {
                            return response || $q.when(response);
                        },
                        'responseError': function(rejection) {
                            // console.log( rejection );
                            return $q.reject(rejection);
                        }


                    };
                    return interceptor;
                }])

            .factory('checkUserPosition', ['$rootScope', function($rootScope) {
                    var service = {
                        getDistance: getDistance
                    };

                    //经纬度转换成三角函数中度分表形式
                    var Rad = function(d) {
                        return d * Math.PI / 180.0;
                    };

                    //计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
                    function getDistance(lat1, lng1, lat2, lng2) {
                        var radLat1 = Rad(lat1);
                        var radLat2 = Rad(lat2);
                        var a = radLat1 - radLat2;
                        var b = Rad(lng1) - Rad(lng2);
                        var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
                                Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
                        s = s * 6378.137;// EARTH_RADIUS;
                        s = Math.round(s * 10000) / 10000; //输出为公里
                        //s=s.toFixed(4);
                        return s;
                    }

                    return service;

                }])

            .factory('weAppDataBase', ['$rootScope', '$q', function($rootScope, $q) {
                    var service = {
                        createDB: createDB,
                        insert: insertDB,
                        update: updateDB,
                        query: queryDB,
                        deleteDB: deleteDB,
                        dropDB: dropDB,
                        cleanDB: cleanDB
                    };

                    var webSQLInfo = {
                        dbName: 'weAppDB',
                        dbVersion: '1.0',
                        dbDisplayName: 'weApp StationLine DataBase',
                        dbEstimatedSize: 1 * 1024 * 1024
                    };

                    var weAppDB = null;

                    /**
                     * 创建数据库
                     * @return {[type]} [description]
                     */
                    function createDB() {
                        weAppDB = window.openDatabase(webSQLInfo.dbName, webSQLInfo.dbVersion, webSQLInfo.dbDisplayName, webSQLInfo.dbEstimatedSize);
                        weAppDB.transaction(function(tx) {
                            tx.executeSql("CREATE TABLE IF NOT EXISTS weAppDB ( lineId TEXT PRIMARY KEY, lineName TEXT, cityMapCode INTEGER, cityName TEXT) ", [],
                                    function(tx, result) {
                                        // console.log("weAppDB created successful.");
                                    },
                                    function(tx, error) {

                                        console.log("weAppDB created error." + error.message);
                                    })
                        })
                    }
                    ;

                    /**
                     * 插入数据
                     * @param  {[type]} lineId      [description]
                     * @param  {[type]} lineName    [description]
                     * @param  {[type]} cityMapCode [description]
                     * @param  {[type]} cityName    [description]
                     * @return {[type]}             [description]
                     */
                    function insertDB(lineId, lineName, cityMapCode, cityName) {
                        weAppDB.transaction(function(tx) {
                            tx.executeSql("INSERT INTO weAppDB ( lineId, lineName, cityMapCode, cityName ) VALUES (?, ?, ?, ?)",
                                    [lineId, lineName, cityMapCode, cityName],
                                    function(tx, result) {
                                        // console.log("insert successful!");
                                    },
                                    function(tx, error) {
                                        // console.log("insert error." + error.message);
                                    })
                        })
                    }
                    ;

                    /**
                     * 更新数据
                     * @return {[type]} [description]
                     */
                    function updateDB() {

                    }
                    ;

                    /**
                     * 检索数据
                     * @param  {[type]} city     [description]
                     * @param  {[type]} lineName [description]
                     * @return {[type]}          [description]
                     */
                    function queryDB(city, lineName) {
                        var sql = "SELECT * FROM weAppDB WHERE cityMapCode = " + city + " AND lineName LIKE '%" + lineName + "%' ";
                        var deferred = $q.defer();
                        weAppDB.transaction(function(tx) {
                            tx.executeSql(sql, [],
                                    function(tx, result) {
                                        deferred.resolve(result.rows);
                                    },
                                    function(tx, error) {
                                        console.warn(error.message);
                                        deferred.reject(error);
                                    })
                        });
                        return deferred.promise;
                    }
                    ;

                    function deleteDB() {
                        var sql = "DELETE FROM weAppDB";
                        var deferred = $q.defer();
                        weAppDB.transaction(function(tx) {
                            tx.executeSql(sql, [],
                                    function(tx, result) {
                                        deferred.resolve(result);
                                    },
                                    function(tx, error) {
                                        // console.warn(error.message);
                                        deferred.reject(error);
                                    })
                        });
                        return deferred.promise;
                    }
                    ;

                    /**
                     * 删除数据库
                     * @return {[type]} [description]
                     */
                    function dropDB() {
                        weAppDB.transaction(function(tx) {
                            tx.executeSql(" DROP TABLE weAppDB ");
                        })
                    }
                    ;

                    function cleanDB() {
                        var sql = "DELETE FROM weAppDB WHERE lineName in ( select lineName frome weAppDB group by lineName having count(lineName) > 1 ) and lineId not in ( select min(lineId) from weAppDB group by lineName having count(lineName) > 1 ) ";
                        weAppDB.transaction(function(tx) {
                            tx.executeSql(sql);
                        });
                    }


                    return service;

                }])

            /**
             * 全局跳转至某个线路详情页面的跳转服务
             */
            .factory('showLinePageService', ['$timeout', '$state', function($timeout, $state) {
                    var service = {
                        gotoLinePage: gotoLinePage
                    };

                    function gotoLinePage(line, event, params) {

                        if (window.sessionStorage) {

                            sessionStorage.setItem("nowLineName", line.lineName);
                            sessionStorage.setItem("clickLine", JSON.stringify(line));
                            $state.go('line', params);

                        } else {
                            console.warn("your browser is not support sessionStorage.");
                        }

                    }

                    return service;
                }])

            /**
             * 全局线路列表中，收藏按钮公用服务
             * 点击收藏后将会将当前线路的ID和线路的JSON数据存入sessionStorage中:
             * @ myFavors        [Array] 收藏ID数组
             * @ myFavorsJSON    [JSON] 收藏JSON数据
             */
            .factory('myFavorsService', ['$timeout', 'localStorageService', function($timeout, localStorageService) {
                    var service = {
                        set: setFavor,
                        getId: getFavorId,
                        getJson: getFavorJson,
                        remove: removeFavor,
                        removeAll: removeFavorAll
                    };

                    /**
                     * 新增一条收藏线路
                     * @param {[type]} line [description]
                     */
                    function setFavor(line) {

                        var tmp_favors = localStorageService.get("myFavors") == null ? [] : JSON.parse(localStorageService.get("myFavors"));
                        tmp_favors.push(line.lineStationId);
                        localStorageService.set("myFavors", JSON.stringify(tmp_favors));

                        var tmp_favorsJSON = localStorageService.get("myFavorsJSON") == null ? [] : JSON.parse(localStorageService.get("myFavorsJSON"));

                        var tmp_stationObj = {
                            "stationId": line.stationId,
                            "stationName": line.stationName,
                            "lineStations": [line]
                        };

                        /**
                         * 如果循环所有已收藏线路都没有找到对应所在站点，则新建一个站点
                         * @type {Boolean}
                         */
                        var mustCreateNewStationObject = true;

                        for (var i = 0; i < tmp_favorsJSON.length; i++) {
                            if (tmp_favorsJSON[i].stationId == line.stationId) {
                                // console.log("have this stationID");
                                tmp_favorsJSON[i].lineStations.push(line);
                                mustCreateNewStationObject = !mustCreateNewStationObject;
                                break;
                            }
                        }

                        /**
                         * 如果循环所有已收藏线路都没有找到对应所在站点，则新建一个站点
                         * @type {Boolean}
                         */
                        if (mustCreateNewStationObject) {
                            // console.log("create a new stationID");
                            tmp_favorsJSON.push(tmp_stationObj);
                        }
                        ;

                        if (!tmp_favorsJSON.length)
                            tmp_favorsJSON.push(tmp_stationObj);

                        // tmp_favorsJSON.push( line );
                        localStorageService.set("myFavorsJSON", JSON.stringify(tmp_favorsJSON));

                        // console.log( tmp_favorsJSON );

                    }
                    ;

                    function getFavorId() {
                        return localStorageService.get("myFavors") == null ? [] : JSON.parse(localStorageService.get("myFavors"));
                    }
                    ;

                    function getFavorJson() {
                        return localStorageService.get("myFavorsJSON") == null ? [] : JSON.parse(localStorageService.get("myFavorsJSON"));
                    }
                    ;

                    /**
                     * 移除一条收藏线路
                     * @param  {[type]} line [description]
                     * @return {[type]}      [description]
                     */
                    function removeFavor(line) {

                        var lineId = line.lineStationId;

                        var tmp_favors = localStorageService.get("myFavors") == null ? [] : JSON.parse(localStorageService.get("myFavors"));
                        var tmp_favorsJSON = localStorageService.get("myFavorsJSON") == null ? [] : JSON.parse(localStorageService.get("myFavorsJSON"));

                        if (tmp_favors == tmp_favorsJSON == null)
                            return;

                        tmp_favors.remove(lineId);
                        localStorageService.set("myFavors", JSON.stringify(tmp_favors));

                        for (var i = 0; i < tmp_favorsJSON.length; i++) {
                            var thisStation = tmp_favorsJSON[i];
                            for (var j = 0; j < thisStation.lineStations.length; j++) {
                                // console.log( thisStation.lineStations[j].lineStationId );
                                if (thisStation.lineStations[j].lineStationId == lineId) {
                                    thisStation.lineStations.splice(j, 1);
                                    break;
                                }
                            }
                            if (!thisStation.lineStations.length)
                                tmp_favorsJSON.splice(i, 1);
                        }

                        localStorageService.set("myFavorsJSON", JSON.stringify(tmp_favorsJSON));

                    }
                    ;

                    /**
                     * 移除全部收藏线路
                     * @return {[type]} [description]
                     */
                    function removeFavorAll() {
                        localStorageService.remove("myFavors");
                        localStorageService.remove("myFavorsJSON");
                    }
                    ;

                    return service;

                }]);


})();
(function() {
    'use strict';

    angular.module('weApp.controllers')


            /**
             * 附近某个站点的线路列表
             * @param  {[type]} $scope   [description]
             * @param  {[type]} $state   [description]
             * @param  {[type]} $timeout [description]
             * @param  {String}          [description]
             * @return {[type]}          [description]
             */
            .controller('stationCtrl', ['$scope', '$state', '$timeout', '$http', 'localStorageService', 'myFavorsService', 'showLinePageService',
                function($scope, $state, $timeout, $http, localStorageService, myFavorsService, showLinePageService) {

                    if (sessionStorage.getItem('clickStation') && sessionStorage.getItem('clickStation') != '') {
                        $scope.stationName = sessionStorage.getItem('nowStationName');
                        $scope.myFavors = localStorageService.get("myFavors") == null ? [] : JSON.parse(localStorageService.get("myFavors"));
                        $scope.myFavorsJSON = localStorageService.get("myFavorsJSON") == null ? [] : JSON.parse(localStorageService.get("myFavorsJSON"));
                    } else {
                        $state.go('index');
                    }

                    $scope.backToIndex = function() {
                        $state.go('index');
                    }

                    //打开线路详细页面（直线图页面）点击事件
                    $scope.showLine = function(line, event) {
                        if (angular.element(event.target).hasClass('station-favor') || angular.element(event.target).hasClass('we-font'))
                            return;
                        showLinePageService.gotoLinePage(line, event);
                    }

                    //线路站点加入收藏事件
                    $scope.tipShown = false;
                    /**
                     * 点击后将该线路加入本地收藏
                     * 收藏的数据将会被存入本地浏览器的LocalStorage中
                     * @param  {[type]} line  [line JSON Data]
                     * @param  {[type]} event [click event]
                     */
                    $scope.favorLine = function(line, event) {
                        //当前点击的lineID;
                        var stationId = line.lineStationId;
                        //如果当前myFavors数组总不含有当前点击的lineID
                        //意为当前点击的线路并未被收藏则执行收藏操作
                        if ($scope.myFavors.indexOf(stationId) == -1) {
                            //通过服务存入LocalStorage
                            myFavorsService.set(line);
                            //存入当前页面临时数组中
                            $scope.myFavors.push(stationId);
                            $scope.tipShown = true;
                            $scope.tipContent = '收藏成功';

                        } else {    //移除操作
                            //通过服务移除LocalStorage中的当前线路
                            myFavorsService.remove(line);
                            //移除临时数组中的ID
                            $scope.myFavors.remove(stationId);
                            $scope.tipShown = true;
                            $scope.tipContent = '取消收藏成功';
                        }

                    }

                    //输出当前站点的线路JSON数据，从sessionStorage中获取
                    $scope.clickStation = JSON.parse(sessionStorage.getItem("clickStation"));


                }])

})();

(function() {
    'use strict';
    angular.module('weApp.controllers')
            //换乘
            .controller('transCtrl', ['$scope', '$rootScope', '$state', '$stateParams', '$timeout', '$http', 'weAppDataBase', 'showLinePageService', 'localStorageService', 'myFavorsService', '$ionicPopup', '$ionicLoading',
                function($scope, $rootScope, $state, $stateParams, $timeout, $http, weAppDataBase, showLinePageService, localStorageService, myFavorsService, $ionicPopup, $ionicLoading) {
                    $rootScope.lineMoney = JSON.parse(localStorageService.get("lineMoney"));
                    if (!$rootScope.lineMoney) {
                        var json = './data/money.json';
                        $http.get(json).success(function(data) {
                            $rootScope.lineMoney = data;
                            localStorageService.set("lineMoney", JSON.stringify(data));
                        });
                    }


                    if (!$rootScope.myAddress) {
                        if (localStorageService.get("myAddress") !== null) {
                            $rootScope.myAddress = JSON.parse(localStorageService.get("myAddress"));
                        }
                    }
                    if ($rootScope.myAddress && !$rootScope.sAddr) {
                        // $rootScope.sAddr = "我的位置";
                        $rootScope.sAddr = {
                            sta: "我的位置",
                            addr: $rootScope.myAddress,
                            end: ""
                        }
                    }
                    if (!$rootScope.sAddr) {
                        $rootScope.sAddr = {};
                    }
                    localStorageService.set("sAddr", JSON.stringify($rootScope.sAddr));
                    if ($stateParams.data || $rootScope.serLoc) {
                        var data = $stateParams.data || $rootScope.serLoc;
                        if (data.sName)
                            // $('#txtBusSta').val(data.sName);
                            $rootScope.sAddr.sta = data.sName;
                        if (data.eName)
                            // $('#txtBusEnd').val(data.eName);
                            $rootScope.sAddr.end = data.eName;
                    }
                    if (!$rootScope.serLoc) {
                        $rootScope.serLoc = {};
                    }
                    $scope.clickSta = function() {
                        console.log('clickSta');
                        $state.go('location', {tit: '请输入起点', tag: 'sta'});
                    }
                    $scope.clickEnd = function() {
                        console.log('clickEnd');
                        $state.go('location', {tit: '请输入终点', tag: 'end'});
                    }
                    /*$scope.clickEnd = function () {
                     console.log('clickEnd');
                     $state.go('transfer', {sta: '宝塔区第一中学', end: '延安第四中学'});
                     }*/
                    $scope.sTransit = function(localTran) {
                        var arr = [];
                        var temp = null;
                        for (var m in localTran) {
                            if (m >= 0) {
                                arr.push(JSON.parse(localTran[m]));
                            }
                        }

                        if (arr.length) {
                            $scope.transit = arr;
                        } else {
                            $scope.transit = [];
                        }
                    }

                    if (localStorageService.get("transitData") !== null) {
                        var localTran = localStorageService.get("transitData") == null ? [] : JSON.parse(localStorageService.get("transitData")).reverse();
                        $scope.sTransit(localTran);
                    } else {
                        localStorageService.set("transit", null);
                        localStorageService.set("transitData", null);
                    }

                    //清空查询历史事件
                    $scope.delSearchConfirm = function() {
                        $ionicPopup.confirm({
                            title: "清空搜索记录",
                            template: "确认清空全部搜索记录吗？",
                            cancelText: "取消",
                            okText: "确定",
                            okType: "button-balanced"
                        }).then(function(res) {
                            if (res) {
                                localStorageService.set("transit", null);
                                localStorageService.set("transitData", null);
                                $scope.transit = [];
                                console.log("clear all histroy!");
                            } else {
                                console.log("clear all histroy has been canceled!");
                            }
                        })
                    }

                    $scope.clickList = function(data) {
                        $rootScope.sAddr.sta = data.sName;
                        $rootScope.sAddr.end = data.eName;
                        $rootScope.serLoc = data;
                        $state.go('transfer', {data: data});
                    }
                    $scope.serChange = function() {
                        var serLoc = null;
                        if ($rootScope.sAddr) {
                            if ($rootScope.sAddr.sta == '我的位置') {
                                if ($rootScope.serLoc.eName) {
                                    $rootScope.sAddr.sta = $rootScope.serLoc.eName;
                                    $rootScope.sAddr.end = '我的位置';
                                    serLoc = {
                                        sta: $rootScope.serLoc.end,
                                        sName: $rootScope.serLoc.eName,
                                        end: $rootScope.sAddr,
                                        eName: $rootScope.sAddr.name
                                    }
                                    $rootScope.serLoc = serLoc;
                                    $state.go('transfer', {data: $rootScope.serLoc});
                                    return false;
                                } else {
                                    $rootScope.sAddr.sta = '';
                                    $rootScope.sAddr.end = '我的位置';
                                }
                            } else if ($rootScope.sAddr.end == '我的位置') {
                                if ($rootScope.serLoc.sName) {
                                    $rootScope.sAddr.end = $rootScope.serLoc.sName;
                                    $rootScope.sAddr.sta = '我的位置';
                                    serLoc = {
                                        end: $rootScope.serLoc.end,
                                        eName: $rootScope.serLoc.eName,
                                        sta: $rootScope.sAddr,
                                        sName: $rootScope.sAddr.name
                                    }
                                    $rootScope.serLoc = serLoc;
                                    $state.go('transfer', {data: $rootScope.serLoc});
                                    return false;
                                } else {
                                    $rootScope.sAddr.sta = '我的位置';
                                    $rootScope.sAddr.end = '';
                                }
                            } else {
                                if ($rootScope.serLoc) {
                                    if ($rootScope.serLoc.sName && $rootScope.serLoc.eName) {
                                        $rootScope.sAddr.sta = $rootScope.serLoc.eName;
                                        $rootScope.sAddr.end = $rootScope.serLoc.sName;
                                        serLoc = {
                                            sta: $rootScope.serLoc.end,
                                            sName: $rootScope.serLoc.eName,
                                            end: $rootScope.serLoc.sta,
                                            eName: $rootScope.serLoc.sName
                                        }
                                        $rootScope.serLoc = serLoc;
                                        $state.go('transfer', {data: $rootScope.serLoc});
                                        return false;
                                    } else if ($rootScope.serLoc.sName) {
                                        $rootScope.sAddr.end = $rootScope.serLoc.sName;
                                        $rootScope.sAddr.sta = '';
                                        serLoc = {
                                            end: $rootScope.serLoc.sta,
                                            eName: $rootScope.serLoc.sName
                                        }
                                        $rootScope.serLoc = serLoc;
                                        return false;
                                    } else if ($rootScope.serLoc.eName) {
                                        $rootScope.sAddr.sta = $rootScope.serLoc.eName;
                                        $rootScope.sAddr.end = '';
                                        serLoc = {
                                            sta: $rootScope.serLoc.end,
                                            sName: $rootScope.serLoc.eName
                                        }
                                        $rootScope.serLoc = serLoc;
                                        return false;
                                    }
                                }
                            }
                        } else {
                            // if ($rootScope.serLoc.sName && $rootScope.serLoc.eName)
                            $rootScope.sAddr = {};
                            if ($rootScope.serLoc) {
                                if ($rootScope.serLoc.sName && $rootScope.serLoc.eName) {
                                    $rootScope.sAddr.sta = $rootScope.serLoc.eName;
                                    $rootScope.sAddr.end = $rootScope.serLoc.sName;
                                    serLoc = {
                                        sta: $rootScope.serLoc.end,
                                        sName: $rootScope.serLoc.eName,
                                        end: $rootScope.serLoc.sta,
                                        eName: $rootScope.serLoc.sName
                                    }
                                    $rootScope.serLoc = serLoc;
                                    $state.go('transfer', {data: $rootScope.serLoc});
                                    return false;
                                } else if ($rootScope.serLoc.sName) {
                                    $rootScope.sAddr.end = $rootScope.serLoc.sName;
                                    $rootScope.sAddr.sta = '';
                                    serLoc = {
                                        end: $rootScope.serLoc.sta,
                                        eName: $rootScope.serLoc.sName
                                    }
                                    $rootScope.serLoc = serLoc;
                                    return false;
                                } else if ($rootScope.serLoc.eName) {
                                    $rootScope.sAddr.sta = $rootScope.serLoc.eName;
                                    $rootScope.sAddr.end = '';
                                    serLoc = {
                                        sta: $rootScope.serLoc.end,
                                        sName: $rootScope.serLoc.eName
                                    }
                                    $rootScope.serLoc = serLoc;
                                    return false;
                                }
                            }
                        }
                    }
                    $scope.serClick = function() {
                        console.log('serClick');
                        if ($rootScope.serLoc.sName && $rootScope.serLoc.eName) {
                            $state.go('transfer', {data: $rootScope.serLoc});
                            return false;
                        } else {
                            $ionicLoading.show({
                                template: '请选择好起止站点后再试'
                            })

                            $timeout(function() {
                                $ionicLoading.hide();
                            }, 2000);
                            return false;
                        }

                    }
                }]);
})();

(function() {
    'use strict';
    angular.module('weApp.controllers')
            //位置
            .controller('locationCtrl', ['$scope', '$rootScope', '$state', '$stateParams', '$timeout', '$http', 'weAppDataBase', '$ionicPopup', '$compile', 'showLinePageService', 'localStorageService', '$ionicLoading',
                function($scope, $rootScope, $state, $stateParams, $timeout, $http, weAppDataBase, $ionicPopup, $compile, showLinePageService, localStorageService, $ionicLoading) {
                    //设置一个键入延迟
                    var keyUpTimeout = null;

                    $scope.tag = $stateParams.tag;
                    $scope.tit = $stateParams.tit;
                    if ($scope.tit && $scope.tag) {
                        localStorageService.set("searchTag", JSON.stringify([$scope.tit, $scope.tag]));
                    } else {
                        var searchTag = JSON.parse(localStorageService.get("searchTag"));
                        $scope.tit = searchTag[0];
                        $scope.tag = searchTag[1];
                    }

                    if (!$rootScope.sAddr) {
                        var sAddr = JSON.parse(localStorageService.get("sAddr"));
                        $rootScope.sAddr = sAddr;
                    }

                    $scope.searchContext = {
                        // keyUpToSearch: false,
                        searchText: ''
                    }
                    $scope.searchLine = function() {
                        if (keyUpTimeout)
                            $timeout.cancel(keyUpTimeout);
                        keyUpTimeout = $timeout(function() {
                            if ($scope.searchContext.searchText != "") {
                                var getCityfromePos = "http://api.map.baidu.com/place/v2/suggestion?city_limit=true&output=json&ak=7vVOlMOKr03PaWX82WajF6mG&callback=JSON_CALLBACK&query=" + $scope.searchContext.searchText + "&region=" + $rootScope.cityCode;

                                $http.jsonp(getCityfromePos)
                                        .then(function(cityPos) {
                                            console.log(JSON.stringify(cityPos.data.result));
                                            // alert("当前详细地址:" + cityPos.data.result);
                                            var num = cityPos.data.result.length;

                                            if (cityPos.data.result.length > 0) {
                                                $scope.serData = [];
                                                var data = cityPos.data.result;
                                                for (var j = 0; j < num; j++) {
                                                    if (data[j].location) {
                                                        $scope.serData.push(data[j])
                                                    }
                                                }
                                            }

                                        }, function(error) {
                                            // $rootScope.appReadyPromise.reject(error);
                                        });
                            }
                        }, 300);

                    }
                    $scope.clickMap = function() {
                        console.log('clickMap');
                        $scope.tag = $stateParams.tag;
                        $scope.tit = $stateParams.tit;
                        if ($scope.tag == 'sta') {
                            var data = {tit: '请选择起点', tag: 'sta'};
                        } else {
                            var data = {tit: '请选择终点', tag: 'end'};
                        }
                        $state.go('map', data);
                    }
                    $scope.clickMy = function() {
                        console.log('#clickMy');
                        if (!$rootScope.sAddr) {
                            $ionicLoading.show({
                                template: '无法获取用户位置'
                            })

                            $timeout(function() {
                                $ionicLoading.hide();
                            }, 2000);
                            return false;
                        }
                        if ($scope.tag == 'sta') {
                            if ($rootScope.serLoc) {
                                $rootScope.serLoc.sta = $rootScope.sAddr.addr;
                                $rootScope.serLoc.sName = $rootScope.sAddr.addr.name;
                                if ($rootScope.serLoc.eName) {
                                    if ($rootScope.serLoc.sName == $rootScope.serLoc.eName) {
                                        $ionicLoading.show({
                                            template: '起点终点不能完全相同'
                                        })

                                        $timeout(function() {
                                            $ionicLoading.hide();
                                        }, 2000);
                                        return false;
                                    } else {
                                        $state.go('transfer', {data: $rootScope.serLoc});
                                        return false;
                                    }
                                }
                            } else {
                                $rootScope.sAddr.sta = '我的位置';
                                $rootScope.sAddr.end = '';
                            }
                        } else if ($scope.tag == 'end') {
                            if ($rootScope.serLoc) {
                                $rootScope.serLoc.end = $rootScope.sAddr.addr;
                                $rootScope.serLoc.eName = $rootScope.sAddr.addr.name;
                                if ($rootScope.serLoc.sName) {
                                    if ($rootScope.serLoc.sName == $rootScope.serLoc.eName) {
                                        $ionicLoading.show({
                                            template: '起点终点不能完全相同'
                                        })

                                        $timeout(function() {
                                            $ionicLoading.hide();
                                        }, 2000);
                                        return false;
                                    } else {
                                        $state.go('transfer', {data: $rootScope.serLoc});
                                        return false;
                                    }
                                }
                            } else {
                                $rootScope.sAddr.sta = '';
                                $rootScope.sAddr.end = '我的位置';
                            }
                        }
                        $state.go('trans', {data: $rootScope.serLoc});
                    }
                    $scope.serCli = function(data) {
                        // console.log(data);
                        if ($scope.tag == 'sta') {
                            $scope.searchContext.searchText = data.name;

                            if ($rootScope.serLoc) {
                                $rootScope.serLoc.sta = {name: data.name, location: data.location};
                                $rootScope.serLoc.sName = data.name;
                            } else {
                                $rootScope.serLoc = {
                                    sta: {name: data.name, location: data.location},
                                    sName: data.name
                                }
                            }
                            if ($rootScope.sAddr.end == "我的位置" && $rootScope.sAddr.addr) {
                                $rootScope.serLoc.end = $rootScope.sAddr.addr;
                                $rootScope.serLoc.eName = $rootScope.sAddr.addr.name;
                                $state.go('transfer', {data: $rootScope.serLoc});
                                return false;
                            }
                        } else if ($scope.tag == 'end') {
                            $scope.searchContext.searchText = data.name;

                            if ($rootScope.serLoc) {
                                $rootScope.serLoc.end = {name: data.name, location: data.location};
                                $rootScope.serLoc.eName = data.name;
                            } else {
                                $rootScope.serLoc = {
                                    end: {name: data.name, location: data.location},
                                    eName: data.name
                                }
                            }
                            if ($rootScope.sAddr.sta == "我的位置" && $rootScope.sAddr.addr) {
                                $rootScope.serLoc.sta = $rootScope.sAddr.addr;
                                $rootScope.serLoc.sName = $rootScope.sAddr.addr.name;
                                $state.go('transfer', {data: $rootScope.serLoc});
                                return false;
                            }
                        }

                        if ($rootScope.serLoc.sName && $rootScope.serLoc.eName) {
                            if ($rootScope.serLoc.sName == $rootScope.serLoc.eName) {
                                $ionicLoading.show({
                                    template: '起点终点不能完全相同'
                                })

                                $timeout(function() {
                                    $ionicLoading.hide();
                                }, 2000);
                                return false;
                            } else {
                                $state.go('transfer', {data: $rootScope.serLoc});
                                return false;
                            }
                        } else {
                            $state.go('trans', {data: $rootScope.serLoc});
                        }
                    }
                    
//                    $scope.$on("$ionicView.enter", function(event, data) {
//                        setTimeout(function() {
//                            $("#s-input").focus();
//                        }, 100)
//                    })
                    setTimeout(function() {
                        $("#s-input").trigger("click").focus();
                    }, 100)
                }]);
})();

(function() {
    'use strict';
    angular.module('weApp.controllers')
            //地图选点
            .controller('mapCtrl', ['$scope', '$rootScope', '$state', '$stateParams', '$timeout', '$http', 'weAppDataBase', '$ionicPopup', '$compile', 'showLinePageService', 'localStorageService', '$ionicLoading',
                function($scope, $rootScope, $state, $stateParams, $timeout, $http, weAppDataBase, $ionicPopup, $compile, showLinePageService, localStorageService, $ionicLoading) {
                    var height = 480;
                    if (screen.height) {
                        height = document.documentElement.clientHeight;
                    }

                    $('#showmap').css('height', height - 44 + 'px');

                    $scope.tag = $stateParams.tag;
                    $scope.tit = $stateParams.tit;
                    if ($scope.tit && $scope.tag) {
                        localStorageService.set("searchTag", JSON.stringify([$scope.tit, $scope.tag]));
                    } else {
                        var searchTag = JSON.parse(localStorageService.get("searchTag"));
                        $scope.tit = searchTag[0];
                        $scope.tag = searchTag[1];
                    }

                    if (!$rootScope.sAddr) {
                        var sAddr = JSON.parse(localStorageService.get("sAddr"));
                        $rootScope.sAddr = sAddr;
                    }

                    /*var he = null;
                     if (screen.height) {
                     he = screen.height - 175;
                     } else {
                     he = 480 - 175;
                     }
                     $('#showmap').css('height', he + 'px');*/

                    $scope.mCon = {
                        name: '',
                        addr: '',
                        location: ''
                    }

                    var map = new BMap.Map("showmap");    // 创建Map实例
                    var pn = new BMap.Point($rootScope.cityLocation.lng, $rootScope.cityLocation.lat);
                    map.centerAndZoom(pn, 17);     // 初始化地图,设置中心点坐标和地图级别
                    map.addControl(new BMap.NavigationControl());       // 添加平移缩放控件
                    map.enableScrollWheelZoom();    //启用滚轮放大缩小
                    var gc = new BMap.Geocoder();
                    var $tit = $('#m-tit');
                    var $addr = $('#m-addr');

                    $scope.fMap = function() {
                        // debugger;
                        // var p=map.getCenter();
//                        var p = new BMap.Point($rootScope.cityLocation.lng, $rootScope.cityLocation.lat);
                        gc.getLocation(pn, function(data) {
                            var tit = null;
                            var point = null;
                            var addr = null;
                            var surr = data.surroundingPois;
                            if (surr.length > 0) {
                                tit = surr[0].title;
                                point = surr[0].point;
                                addr = surr[0].address;
                                $tit.html(tit);
                                $addr.html(addr);
                                $scope.mCon = {
                                    name: tit,
                                    addr: addr,
                                    location: point
                                }
                            } else {
                                $scope.mCon.name = '';
                                $tit.html('');
                                $addr.html('');
                            }
                        }, {poiRadius: 500, numPois: 1});
                    }
                    $scope.fMap();

                    map.addEventListener("dragend", function(e) {
                        var p = map.getCenter();
                        gc.getLocation(p, function(data) {
                            var tit = null;
                            var point = null;
                            var addr = null;
                            var surr = data.surroundingPois;
                            if (surr.length > 0) {
                                tit = surr[0].title;
                                point = surr[0].point;
                                addr = surr[0].address;
                                $tit.html(tit);
                                $addr.html(addr);
                                $scope.mCon = {
                                    name: tit,
                                    addr: addr,
                                    location: point
                                }
                            } else {
                                $scope.mCon.name = '';
                                $tit.html('');
                                $addr.html('');
                            }
                        }, {poiRadius: 1000, numPois: 1});
                    });


                    $scope.cMap = function() {
                        // console.log('cMap');
                        if (!$scope.mCon.name) {
                            $ionicLoading.show({
                                template: '未检索到位置'
                            })

                            $timeout(function() {
                                $ionicLoading.hide();
                            }, 1000);
                            return false;
                        }
                        var data = $scope.mCon;
                        if ($scope.tag == 'sta') {
                            // $scope.searchContext.searchText = data.name;

                            if ($rootScope.serLoc) {
                                $rootScope.serLoc.sta = {name: data.name, location: data.location};
                                $rootScope.serLoc.sName = data.name;
                            } else {
                                $rootScope.serLoc = {
                                    sta: {name: data.name, location: data.location},
                                    sName: data.name
                                }
                            }
                            if ($rootScope.sAddr.end == "我的位置" && $rootScope.sAddr.addr) {
                                $rootScope.serLoc.end = $rootScope.sAddr.addr;
                                $rootScope.serLoc.eName = $rootScope.sAddr.addr.name;
                                $state.go('transfer', {data: $rootScope.serLoc});
                                return false;
                            }
                        } else if ($scope.tag == 'end') {
                            // $scope.searchContext.searchText = data.name;

                            if ($rootScope.serLoc) {
                                $rootScope.serLoc.end = {name: data.name, location: data.location};
                                $rootScope.serLoc.eName = data.name;
                            } else {
                                $rootScope.serLoc = {
                                    end: {name: data.name, location: data.location},
                                    eName: data.name
                                }
                            }
                            if ($rootScope.sAddr.sta == "我的位置" && $rootScope.sAddr.addr) {
                                $rootScope.serLoc.sta = $rootScope.sAddr.addr;
                                $rootScope.serLoc.sName = $rootScope.sAddr.addr.name;
                                $state.go('transfer', {data: $rootScope.serLoc});
                                return false;
                            }
                        }

                        if ($rootScope.serLoc.sName && $rootScope.serLoc.eName) {
                            if ($rootScope.serLoc.sName == $rootScope.serLoc.eName) {
                                $ionicLoading.show({
                                    template: '起点终点不能完全相同'
                                })

                                $timeout(function() {
                                    $ionicLoading.hide();
                                }, 2000);
                                return false;
                            } else {
                                $state.go('transfer', {data: $rootScope.serLoc});
                                return false;
                            }
                        } else {
                            $state.go('trans', {data: $rootScope.serLoc});
                        }
                    }
                }]);
})();

(function() {
    'use strict';
    angular.module('weApp.controllers')
            //线路换乘详情
            .controller('transferCtrl', ['$scope', '$rootScope', '$state', '$stateParams', '$timeout', '$http', 'weAppDataBase', '$ionicPopup', '$compile', 'showLinePageService', 'localStorageService', '$ionicLoading', '$interval',
                function($scope, $rootScope, $state, $stateParams, $timeout, $http, weAppDataBase, $ionicPopup, $compile, showLinePageService, localStorageService, $ionicLoading, $interval) {

                    if (!$rootScope.lineMoney) {
                        $rootScope.lineMoney = JSON.parse(localStorageService.get("lineMoney"));
                    }

                    var data = $stateParams.data;
                    if (data) {
                        localStorageService.set("searchTrans", JSON.stringify(data));
                    } else {
                        data = JSON.parse(localStorageService.get("searchTrans"));
                    }

                    $scope.tit1 = data.sName;
                    $scope.tit2 = data.eName;
                    $scope.sData = {
                        title: data.sName,
                        point: new BMap.Point(data.sta.location.lng, data.sta.location.lat)
                    };
                    $scope.eData = {
                        title: data.eName,
                        point: new BMap.Point(data.end.location.lng, data.end.location.lat)
                    };

//                if (screen.height)
//                    $('#m-desc').css('height', screen.height + 'px');

                    $scope.route = 'time';

                    $scope.lines = null;
                    $scope.linebus = null;


                    var $sta = $('#txtBusSta');
                    var $end = $('#txtBusEnd');
                    var busStaValue;
                    var busEndValue;

                    //百度地图api
                    var map = new BMap.Map("allmap");    // 创建Map实例
                    map.centerAndZoom($rootScope.cityName, 13);     // 初始化地图,设置中心点坐标和地图级别
                    map.addControl(new BMap.NavigationControl());       // 添加平移缩放控件
                    map.enableScrollWheelZoom();    //启用滚轮放大缩小
                    $scope.searchTransit = function(start, end, type) {
                        $interval.cancel($rootScope.siteTimes);
                        console.log("定时刷新被移除了.");
                        var route = null;
                        var str = null;
                        var str2 = null;
                        var num = 0;

                        var routePolicy = [BMAP_TRANSIT_POLICY_LEAST_TIME, BMAP_TRANSIT_POLICY_LEAST_TRANSFER, BMAP_TRANSIT_POLICY_LEAST_WALKING, BMAP_TRANSIT_POLICY_AVOID_SUBWAYS];
                        if (type == 0) {
                            route = routePolicy[0];
                            $scope.route = 'time';
                        } else if (type == 1) {
                            route = routePolicy[1];
                            $scope.route = 'transfer';
                        } else if (type == 2) {
                            route = routePolicy[2];
                            $scope.route = 'walk';
                        } else {
                            route = routePolicy[0];
                            $scope.route = 'time';
                        }
                        map.clearOverlays();
                        var transit = new BMap.TransitRoute(map, {
                            renderOptions: {map: map, panel: "tran-result"},
                            policy: route,
                            onResultsHtmlSet: function(result) {

                                var res = get_money(result);
                                $('#tran-result2').html(res);
                                // $('#bottom-tabs').hide();
                                // $('#line-bar,#res-line').animate({left: 0});
                                // $('#tran-main').addClass('con-right');
                                $scope.get_time();
                                // $rootScope.siteTimes = setInterval(get_time, 10000);
                                $rootScope.siteTimes = $interval(function() {
                                    $scope.$broadcast("refreshTime");
                                }, 20000);
                            },
                            onSearchComplete: function(result) {
                                if (result) {
                                    num = result.getNumPlans();

                                    if (num > 0) {
                                        var localTran = localStorageService.get("transit") == null ? [] : JSON.parse(localStorageService.get("transit"));
                                        var localTranData = localStorageService.get("transitData") == null ? [] : JSON.parse(localStorageService.get("transitData"));
                                        str = start.title + '@*@' + end.title;
                                        str2 = JSON.stringify($stateParams.data);
                                        if (localTran.indexOf(str) == -1) {
                                            localTran.push(str);
                                            localStorageService.set("transit", JSON.stringify(localTran));
                                            localTranData.push(str2);
                                            localStorageService.set("transitData", JSON.stringify(localTranData));
                                        }
                                    } else {
                                        var myPopu = $ionicPopup.show({
                                            title: "未查询到相应换乘线路",
                                            cssClass: "validate"
                                        });

                                        $timeout(function() {
                                            myPopu.close();
                                        }, 3000);
                                    }
                                }
                            }
                        });

                        transit.search(start, end);
                    }

                    $scope.$on("refreshTime", function(event, data) {
                        var time = Date.parse(new Date());
                        if (!$scope.gtime) {
                            $scope.gtime = time;
                        } else {
                            var tag = time - $scope.gtime;
                            if (tag >= 20000) {
                                $scope.gtime = time;
                            } else {
                                console.log(time);
                                console.log(tag);
                                console.log('不执行get_time');
                                return false;
                            }
                        }
                        console.log(time);
                        console.log(tag);
                        console.log('执行get_time');
                        $scope.get_time();
                    });

                    ///////////////////////////////////////////
                    $scope.searchTransit($scope.sData, $scope.eData);

                    //////////////////////////////////////////
                    function in_array(search, arr) {
                        for (var i in arr) {
                            if (arr[i].line == search) {
                                return arr[i];
                            }
                        }
                        return false;
                    }

                    //插入money
                    function get_money(result) {
                        var lines = [];
                        var line = [];
                        var $res = $(result);
                        var $list = $res.find('.trans-title');
                        var arr = null;
                        var money = null;
                        var str = null;
                        var sName = null;
                        var eName = null;
                        $list.each(function(i, n) {
                            money = 0;
                            var html = $(this).find('p').get(0).innerHTML;
                            var $next = $($(this).find('p').get(1));
                            if (html.indexOf('地铁') >= 0) {
                                // $(this).parent().parent().parent().addClass('noplay');
                                $(this).parent().parent().parent().remove();
                            } else {
                                $(this).parent('div').css({
                                    'border': 'none',
                                    'border-bottom': '1px solid rgb(228, 230, 231)'
                                });
                                //开、结站点
                                var $table = $(this).siblings('div').find('.trans-plan-content');
                                var fir = $(this).siblings('div').find('.nav-st').siblings('div').html();
                                var tag = $table.find('.navtrans-bus-desc').get(0).innerHTML;
                                if (tag.indexOf('步行') >= 0) {
                                    sName = ($table.find('.navtrans-busstation').get(0).innerHTML).replace('站', "");
                                    eName = ($table.find('.navtrans-busstation').get(2).innerHTML).replace('站', "");
                                } else {
                                    sName = fir.replace('站', "");
                                    eName = ($table.find('.navtrans-busstation').get(1).innerHTML).replace('站', "");
                                }

                                arr = html.split(' → ');
                                for (var n in arr) {
                                    if (n >= 0) {
                                        /*if (arr[n].charAt(0) == 'K' || arr[n].charAt(0) == 'k') {
                                         money += 2;
                                         } else {
                                         money += 1;
                                         }*/
                                        if ($rootScope.lineMoney) {
                                            var obj = in_array(arr[n].replace('路', ""), $rootScope.lineMoney);
                                            if (obj) {
                                                money += obj.money * 1;
                                            }
                                        }

                                        if (n == 0) {
                                            lines.push({
                                                lineName: arr[n].replace('路', ""),
                                                startStationName: sName,
                                                endStationName: eName
                                            });
                                            line.push(arr[n]);
                                        }
                                    }
                                }

                                $scope.lines = lines;
                                $scope.linebus = line;
                                if (money * 1 > 0) {
                                    str = '&nbsp;|&nbsp;' + money + '元<br/><label class="site"></label>';
                                } else {
                                    str = '<br/><label class="site"></label>';
                                }

                                $next.append(str);
                            }
                        })
                        return $res;
                    }

                    $scope.get_time = function() {
                        var rootR = {
                            method: 'post',
                            url: $rootScope.rootLocation + '/line/bus/transferPredictList',
                            data: {
                                "cityCode": $rootScope.cityCode,
                                "lines": $scope.lines
                            }
                        };

                        $http(rootR).then(function(boards) {
                            if (boards.data.head.success == "true") {
                                var arr = [];
                                var board = boards.data.data.lineTransferPredicts;
                                for (var i in board) {
                                    if (i >= 0) {
                                        var m = board[i].busStatus * 1;
                                        switch (m) {
                                            case 1:
                                                arr.push({txt: board[i].startStationName + '上车&nbsp;&nbsp;' + $scope.linebus[i] + '&nbsp;&nbsp;<span style="color:red;">即将到站</span>'});
                                                break;
                                            case 2:
                                                arr.push({txt: board[i].startStationName + '上车&nbsp;&nbsp;' + $scope.linebus[i] + '&nbsp;&nbsp;<span style="color:red;">' + board[i].diffSeq + '站/' + board[i].arrivalTime + '分钟</span>后到达'});
                                                break;
                                            case 4:
                                                arr.push({txt: board[i].startStationName + '上车&nbsp;&nbsp;' + $scope.linebus[i] + '&nbsp;&nbsp;<span style="color:red;">等待发车</span>'});
                                                break;
                                            case 5:
                                                arr.push({txt: ''});
                                                break;
                                            default:

                                        }
                                    }
                                }
                                $('#tran-result2 .site').each(function(i) {
                                    if (i >= 0 && arr[i]) {
                                        $(this).html(arr[i].txt);
                                    }
                                })
                                // $rootScope.board = board;
                            }

                        });
                    }

                    $("#tran-result2").delegate(".tranroute-plan-list", "click", function() {
                        var tr = null;
                        $('div.trans_plan_desc').removeClass('line-show');
                        $('#tran-result3').html('');
                        $('#barf').css('z-index', 0);
                        var $div = $(this).find('div.trans_plan_desc');
                        // var tag = $div[0].style.display;
                        // if (tag == 'none') {
                        // $div.addClass('line-show');
                        $('#m-desc').css({top: '380px'});
                        $('#detail-bar,#res-detail').animate({left: 0});
                        $timeout(function() {
                            $('#res-line').hide();
                        }, 300);
                        tr = $(this).html();
                        $('#tran-result3').html(tr);
                        $('#tran-result3 .site').remove();
                        var prev = null;
                        var $prev = null;
                        $scope.cLine = [];
                        $('#tran-result3 .navtrans-bus-icon').each(function(i, n) {
                            var $h = $(this).next('div');
                            var h = $h.html();
                            var t = h.match(/\d+站/g);
                            var str = '';
                            if (t) {
                                t = t[0];
                                var u = t.substring(0, t.length - 1);
                                // if (u * 1 > 1) {
                                if (prev && $prev) {
                                    // prev = prev + '<i class="we-font we-icon-rounddown ic-don" data="' + $scope.cLine.length + '"></i><div class="i-down" style="display: none;"></div>';
                                    // $prev.html(prev);
                                    var sn = $prev.find('.navtrans-busstation').html();

                                    var line = $h.find('.navtrans-busstation').get(0).innerHTML;
                                    var en = $h.find('.navtrans-busstation').get(1).innerHTML;

                                    //拼字符串
                                    str = str + '<tr class="tr-bus"><td><span class="navtrans-bus-icon2 bus"></span><div class="navtrans-bus-desc"><span class="navtrans-busstation">' + sn + '</span>上车</div></td> </tr>';
                                    if (u * 1 > 1) {
                                        $scope.cLine.push({
                                            line: line,
                                            sn: sn,
                                            en: en,
                                            num: u
                                        });
                                        str = str + '<tr class="tr-bus"><td><span class="navtrans-bus-icon2 bline"></span><div class="navtrans-bus-desc"><span>' + line + '</span><span class="ic-donw ic-don" data="' + ($scope.cLine.length - 1) + '">' + u + '站<i class="we-font we-icon-rounddown" ></i></span><div class="n-desc"></div></div></td></tr>';
                                    } else {
                                        str = str + '<tr class="tr-bus"><td><span class="navtrans-bus-icon2 bline"></span><div class="navtrans-bus-desc"><span>' + line + '</span><span class="ic-donw">' + u + '站</span></div></td></tr>';
                                    }
                                    str = str + '<tr class="tr-bus"><td><span class="navtrans-bus-icon2 bus"></span><div class="navtrans-bus-desc"><span class="navtrans-busstation">' + en + '</span>下车</div></td> </tr>';
                                    var par = $(this).parent().parent();
                                    par.after(str);
                                    par.remove();
                                }
                                // }
                            } else {
                                prev = h;
                                $prev = $h;
                            }
                        });
                        // } else {
                        //     $div.removeClass('line-show');
                        // }
                    });
                    var busline = new BMap.BusLineSearch($rootScope.cityName, {
                        onGetBusListComplete: function(result) {
                            if (result) {

                                for (var i = 0, num = result.getNumBusList(); i < num; i++) {
                                    var item = result.getBusListItem(i);
                                    busline.getBusLine(item);
                                }
                                busline.setGetBusLineCompleteCallback(function(lineResults) {
                                    var jsonObj = lineResults;
                                    var BusStaions = [];
                                    var str = '';
                                    for (var i = 0; i < jsonObj.AB.length; i++) {
                                        BusStaions.push(jsonObj.AB[i].name);
                                    }
                                    // console.log("result:" + BusStaions.join(','));
                                    // $scope.busSite.push(BusStaions);
                                    var n = BusStaions.length;
                                    if (n > 0 && $scope.oneBus.sn && $scope.oneBus.en) {
                                        var f = BusStaions.indexOf($scope.oneBus.sn);
                                        var e = BusStaions.indexOf($scope.oneBus.en);
                                        if (f >= 0 && e >= 0 && f < e) {
                                            for (var i = 0; i < n; i++) {
                                                if (i > f && i < e)
                                                    $scope.busSite.push(BusStaions[i]);

                                            }
                                            var p = $scope.busSite.length;
                                            for (var k = 0; k < p; k++) {
                                                str = str + '<div class="n-one"><span class="n-site"></span>' + $scope.busSite[k] + '</div>';
                                            }
                                            $scope.dSite.html(str);
                                            return false;
                                        }
                                    }
                                    $ionicLoading.hide();
                                });
                            }

                        }
                    });
                    $("#tran-result3").delegate(".ic-don", "click", function() {
                        // console.log('ic-don');
                        var i = $(this).attr('data');
                        $scope.dSite = $(this).next('.n-desc');
                        var h = $(this).next('.n-desc').html();
                        if ($scope.cLine[i] && !h) {
                            get_site($scope.cLine[i]);

                        }
                        $scope.dSite.toggle();

                    })
                    function get_site(obj) {
                        $ionicLoading.show({
                            template: '读取中...'
                        })
                        $scope.busSite = [];
                        $scope.oneBus = obj;
                        busline.getBusList(obj.line);
                    }

                    $('#detail-back').click(function() {
                        $('#res-line').show();
                        $('#res-line').attr({style: "left:0"});
                        $('#detail-bar,#res-detail').animate({left: '100%'});
                        $('#barf').css('z-index', 9);
                        $('#m-desc').animate({top: '380px'});
                    })

                    $scope.changeType = function(type) {
                        $scope.searchTransit($scope.sData, $scope.eData, type);
                    }

                    $('#m-nav').click(function() {
                        var top = $('#m-desc').css('top');
                        if (top == '0px') {
                            $('#m-desc').animate({top: '380px'});
                            setTimeout(function() {
                                $('#allmap').css('height','406px');
                            },100)
                        } else {
                            $('#m-desc').animate({top: '0px'});
                            setTimeout(function() {
                                $('#allmap').css('height','330px');
                            }, 100)
                            
                        }
                    })

                    $scope.$on('$destroy', function() {
                        console.log("定时刷新被移除了.");
                        $interval.cancel($rootScope.siteTimes);
                    });
                }])

})();

(function() {
    'use strict';
    angular.module('weApp.controllers')
            //公告栏
            .controller('boardCtrl', ['$scope', '$rootScope', '$state', '$stateParams', '$timeout', '$http', 'weAppDataBase', 'showLinePageService', 'localStorageService', 'myFavorsService', '$ionicLoading',
                function($scope, $rootScope, $state, $stateParams, $timeout, $http, weAppDataBase, showLinePageService, localStorageService, myFavorsService, $ionicLoading) {
                    var look = localStorageService.get("noticeId") == null ? [] : JSON.parse(localStorageService.get("noticeId"));
                    var rootR = {
                        method: 'post',
                        url: $rootScope.rootLocation + '/line/bus/notices',
                        data: {
                            "cityName": $rootScope.cityName,
                            "cityCode": $rootScope.cityCode
                        }
                    };
                    if (!$rootScope.board) {
                        $ionicLoading.show({
                            template: '读取中...'
                        }).then(function() {
                            $http(rootR).then(function(boards) {
                                $ionicLoading.hide();
                                if (boards.data.head.success == "true") {
                                    var board = boards.data.data.notices;

                                    for (var i in board) {
                                        if (i >= 0) {
                                            board[i].noticeContents = board[i].noticeContent.substr(0, 60) + '...';
                                            board[i].noticeContentd = board[i].noticeContent.replace(/\n/g, "<br/>")
                                        }
                                        if (look.length > 0) {
                                            if (look.indexOf(board[i].noticeId) >= 0) {
                                                board[i].tag = 1;
                                            } else {
                                                board[i].tag = 0;
                                            }
                                        }
                                    }
                                    $rootScope.board = board;
                                }

                            });
                        });
                    } else {
                        var board = $rootScope.board;
                        for (var i in board) {
                            if (i >= 0) {
                                board[i].noticeContents = board[i].noticeContent.substr(0, 60) + '...';
                                board[i].noticeContentd = board[i].noticeContent.replace(/\n/g, "<br/>")
                            }
                            if (look.length > 0) {
                                if (look.indexOf(board[i].noticeId) >= 0) {
                                    board[i].tag = 1;
                                } else {
                                    board[i].tag = 0;
                                }
                            }
                        }
                        $rootScope.board = board;
                    }


                    //下拉刷新
                    $rootScope.doRefresh = function() {
                        $http(rootR).then(function(boards) {
                            if (boards.data.head.success == "true") {
                                var board = boards.data.data.notices;
                                for (var i in board) {
                                    if (i >= 0) {
                                        board[i].noticeContents = board[i].noticeContent.substr(0, 60) + '...';
                                        board[i].noticeContentd = board[i].noticeContent.replace(/\n/g, "<br/>")
                                    }
                                    if (look.length > 0) {
                                        if (look.indexOf(board[i].noticeId) >= 0) {
                                            board[i].tag = 1;
                                        } else {
                                            board[i].tag = 0;
                                        }
                                    }
                                }
                                $rootScope.board = board;
                            }

                        })
                                .finally(function() {
                                    $scope.$broadcast('scroll.refreshComplete');
                                });

                    }

                    $rootScope.details = function(title, content, id) {
                        $rootScope.title = title;
                        $rootScope.content = content;
                        localStorageService.set("noticeTit", title);
                        localStorageService.set("noticeCon", content);
                        var localTran = localStorageService.get("noticeId") == null ? [] : JSON.parse(localStorageService.get("noticeId"));
                        // str = start + '@*@' + end;
                        if (localTran.indexOf(id) == -1) {
                            localTran.push(id);
                            localStorageService.set("noticeId", JSON.stringify(localTran));
                        }
                    }


                }]);
})();

(function() {
    'use strict';
    angular.module('weApp.controllers')
            //公告栏
            .controller('boardContentCtrl', ['$scope', '$rootScope', 'localStorageService',
                function($scope, $rootScope, localStorageService) {
                    if (!$rootScope.title) {
                        $rootScope.title = localStorageService.get("noticeTit");
                        $rootScope.content = localStorageService.get("noticeCon");
                    }
                    $('#c-title').html($rootScope.title);
                    $('#c-text').html($rootScope.content);
                }]);
})();

(function() {
    'use strict';
    angular.module('weApp.controllers')
            //评价
            .controller('assessCtrl', ['$ionicActionSheet', '$ionicPopup', '$scope', '$rootScope', '$state', '$stateParams', '$timeout', '$http', 'weAppDataBase', 'showLinePageService', 'localStorageService', 'myFavorsService',
                function($ionicActionSheet, $ionicPopup, $scope, $rootScope, $state, $stateParams, $timeout, $http, weAppDataBase, showLinePageService, localStorageService, myFavorsService) {

                    if ($rootScope.lineData) {
                        localStorageService.set("lineData", JSON.stringify($rootScope.lineData));
                    } else {
                        $rootScope.lineData = JSON.parse(localStorageService.get("lineData"));
                    }

                    if ($rootScope.busNums) {
                        localStorageService.set("busNums", JSON.stringify($rootScope.busNums));
                    } else {
                        $rootScope.busNums = JSON.parse(localStorageService.get("busNums"));
                    }

                    //车辆投诉上拉弹窗
                    $scope.show = function() {
                        var obj = {};
                        obj.buttons = [];
                        obj.titleText = '请选择投诉车辆(默认为线路投诉)';
                        obj.cancelText = '取消';
                        obj.cancel = function() {
                        };
                        obj.buttonClicked = function(i) {
                            if (i > 0) {
                                $scope.busNum = $rootScope.busNums[i - 1].busNum;
                                $('.select').html($scope.busNum);
                            } else {
                                $('.select').html('请选择投诉车辆(默认为线路投诉)');
                                $scope.busNum = '';
                            }
                            return true;
                        };
                        obj.buttons.push({text: '<span class="ass-t">请选择投诉车辆(默认为线路投诉)</span>'});
                        for (var i in $rootScope.busNums) {
                            if (i >= 0)
                                obj.buttons.push({text: $rootScope.busNums[i].busNum});
                        }
                        var hideSheet = $ionicActionSheet.show(obj);

                    }

                    //获取投诉列表
                    var feedReq = {
                        method: 'post',
                        url: $rootScope.rootLocation + '/line/bus/feedbackList',
                        data: {
                            "cityName": $rootScope.cityName,
                            "cityCode": $rootScope.cityCode,
                            "problemType": '1'
                        }
                    };

                    $http(feedReq).then(function(feedInfos) {
                        if (feedInfos.data.head.success == "true") {
                            $scope.feedInfo = feedInfos.data.data.problems;
                        }

                    });


                    //投诉复选
                    var content = {};
                    var problem = {}
                    var a = document.getElementById("group");
                    var list = a.querySelectorAll("button");
                    $rootScope.feedBox = function(e, i, text, prob) {
                        var t = $(e.currentTarget);
                        t.toggleClass('active');
                        if (t.is('.active')) {
                            content[text] = 0;
                            problem[prob] = 0;
                        } else {
                            delete content[text];
                            delete problem[prob];
                        }
                    }


                    //车辆投诉提交
                    $scope.feedCar = function() {

                        var desc = $("#desc").val();
                        if (desc) {
                            content[desc] = 0;
                        }
                        //表单验证
                        if ($.isEmptyObject(content)) {
                            var myPopup = $ionicPopup.show({
                                title: "友情提示",
                                template: "请填写内容后再试",
                                cssClass: "validate"
                            });

                        }
                        if (myPopup) {
                            $timeout(function() {
                                myPopup.close();
                            }, 2000);
                            return false;
                        }
                        $scope.content = Object.keys(content).join(',');
                        $scope.problemId = Object.keys(problem).join();
                        var rootCar = {
                            method: 'post',
                            url: $rootScope.rootLocation + '/line/bus/complaint',
                            data: {
                                "selfNum": " ",
                                "busNum": $scope.busNum,
                                "lineName": $rootScope.lineData.lineName,
                                "lineId": $rootScope.lineData.lineId,
                                "content": $scope.content,
                                "problemId": $scope.problemId
                            }
                        };

                        $http(rootCar).then(function(data) {
                            var myPopu = $ionicPopup.show({
                                title: "温馨提示",
                                template: "评价成功!",
                                cssClass: "validate"
                            });

                            $timeout(function() {
                                myPopu.close();
                            }, 2000);
                            window.history.back();

                        });


                    }


                }]);
})();


(function() {
    'use strict';
    angular.module('weApp.controllers')
            //帮助中心
            .controller('helpCtrl', ['$scope', '$rootScope', '$state', '$stateParams', '$timeout', '$http', 'weAppDataBase', 'showLinePageService', 'localStorageService', 'myFavorsService',
                function($scope, $rootScope, $state, $stateParams, $timeout, $http, weAppDataBase, showLinePageService, localStorageService, myFavorsService) {

                    var rootReq = {
                        method: 'post',
                        url: $rootScope.rootLocation + '/line/bus/feedbackList',
                        data: {
                            "cityName": $rootScope.cityName,
                            "cityCode": $rootScope.cityCode,
                            "problemType": '2'
                        }
                    };

                    $http(rootReq).then(function(helps) {
                        if (helps.data.head.success == "true") {
                            var help = helps.data.data.problems;
                            for (var i in help) {
                                help[i].commTitles = help[i].commTitle;
                                if (i >= 0) {
                                    if (help[i].commTitle.length > 16) {
                                        help[i].commTitle = help[i].commTitle.slice(0, 14) + "...";
                                    }

                                }
                            }

                            $rootScope.help = help;
                        }

                    });

                    $scope.btn = function(title, text, titles) {
                        $rootScope.text = text;
                        $rootScope.titles = titles;
                        localStorageService.set("helpTit", titles);
                        localStorageService.set("helpTxt", text);
                    }

                }]);
})();

(function() {
    'use strict';
    angular.module('weApp.controllers')
            //帮助内容
            .controller('helpContentCtrl', ['$scope', '$rootScope', 'localStorageService',
                function($scope, $rootScope, localStorageService) {
                    if (!$rootScope.titles) {
                        $rootScope.text = localStorageService.get("helpTxt");
                        $rootScope.titles = localStorageService.get("helpTit");
                    }
                    $('#he-tit').html($rootScope.titles);
                    $('#he-txt').html($rootScope.text);
                }]);
})();

(function() {
    'use strict';

    angular.module('weApp.controllers')

            //问题反馈
            .controller('questionCtrl', ['$scope', '$ionicPopup', '$rootScope', '$state', '$stateParams', '$timeout', '$http', 'weAppDataBase', 'showLinePageService', 'localStorageService', 'myFavorsService',
                function($scope, $ionicPopup, $rootScope, $state, $stateParams, $timeout, $http, weAppDataBase, showLinePageService, localStorageService, myFavorsService) {

                    var resize = function(image, scale, type) {
                        var canvas = document.createElement('canvas');
                        canvas.width = image.width * scale;
                        canvas.height = image.height * scale;
                        var context = canvas.getContext('2d');
                        context.clearRect(0, 0, image.width, image.height);
                        context.drawImage(image, 0, 0, canvas.width, canvas.height);
                        var data = canvas.toDataURL(type);
                        return base64ToBlob(data);
                    }

                    /**
                     *
                     * @type {tools.base64ToBlob}
                     */
                    var base64ToBlob = function(urlData) {
                        var mimeString = urlData.split(',')[0].split(':')[1].split(';')[0]; // mime类型
                        var byteString = atob(urlData.split(',')[1]); //base64 解码
                        var arrayBuffer = new ArrayBuffer(byteString.length); //创建缓冲数组
                        var intArray = new Uint8Array(arrayBuffer); //创建视图
                        for (var i = 0; i < byteString.length; i += 1) {
                            intArray[i] = byteString.charCodeAt(i);
                        }
                        var blob = new Blob([intArray], {type: mimeString}); //转成blob
                        return blob;
                    }
                    //图片预览

                    $("#file").change(function() {
                        var objUrl = getObjectURL(this.files[0]);
                        if (objUrl) {
                            $("#show").attr("src", objUrl).show();
                        }
                    });

                    function getObjectURL(file) {
                        var url = null;
                        if (window.createObjectURL != undefined) { // basic
                            url = window.createObjectURL(file);
                        } else if (window.URL != undefined) { // mozilla(firefox)
                            url = window.URL.createObjectURL(file);
                        } else if (window.webkitURL != undefined) { // webkit or chrome
                            url = window.webkitURL.createObjectURL(file);
                        }
                        return url;
                    }

                    //图片缩放
                    $scope.scale = function(args) {
                        var oImg = document.getElementById("show");
                        if (oImg.src) {
                            if (args) {
                                oImg.width = oImg.width * 1.1;
                                oImg.height = oImg.height * 1.1;
                            }
                            else {
                                oImg.width = oImg.width / 1.1;
                                oImg.height = oImg.height / 1.1;
                            }

                        }

                    }
                    $scope.tag = true;
                    $scope.quest = function() {
                        if ($scope.tag) {
                            $scope.tag = false;
                        } else {
                            return false;
                        }
                        //单验证
                        var question = $scope.feedback;
                        var qq = $scope.contactMethod;
                        if (!question) {
                            var myPopup = $ionicPopup.show({
                                title: "温馨提示",
                                template: "亲,请您写点意见吧",
                                cssClass: "validate"
                            });
                        } else if (!qq) {
                            var myPopup = $ionicPopup.show({
                                title: "温馨提示",
                                template: "亲,请留个联系方式吧",
                                cssClass: "validate"
                            });
                        }
                        if (myPopup) {
                            $timeout(function() {
                                myPopup.close();
                            }, 2000);
                            return false;
                        }
                        if ($("#file").val()) {
                            var data = new FormData($('#form')[0]);
                            var url = window.URL.createObjectURL($("#file")[0].files[0]);
                            $scope.myPopu = $ionicPopup.show({
                                title: "提交中",
                                cssClass: "validate"
                            });

                            $('#hide_img').one('load', function() {
                                for (var i = 0; i < 10; i++) {

                                    var imagedata = resize(this, (10 - (i + 1)) / 10, 'image/png');
                                    if (imagedata.size <= 1024 * 1024) {
                                        var image = imagedata;
                                        var formData = new FormData();
                                        var names = $("#file").val().split("\\");
                                        names = names[names.length - 1];
                                        //+"." + mimeType[imagedata.type]
                                        formData.append($("#file")[0].name, imagedata, names);
                                        formData.append("cityName", $rootScope.cityName);
                                        formData.append("cityCode", $rootScope.cityCode);
                                        formData.append("feedback", $scope.feedback);
                                        formData.append("contactMethod", $scope.contactMethod);

                                        $.ajax({
                                            contentType: false,
                                            processData: false,
                                            url: $rootScope.rootLocation + '/line/bus/new/feedback',
                                            type: 'POST',
                                            data: formData,
                                            success: function(res) {
                                                $scope.tag = true;
                                                $scope.myPopu.close();
                                                if (res.head.success == "true") {
                                                    var myPopu = $ionicPopup.show({
                                                        title: "提交成功",
                                                        cssClass: "validate"
                                                    });

                                                    $timeout(function() {
                                                        myPopu.close();
                                                    }, 1000);
                                                    window.history.back();
                                                } else {
                                                    var myPopu = $ionicPopup.show({
                                                        title: "提交失败",
                                                        cssClass: "validate"
                                                    });
                                                    $timeout(function() {
                                                        myPopu.close();
                                                    }, 1000);
                                                }
                                            },
                                            error: function(res) {
                                                $scope.tag = true;
                                                $scope.myPopu.close();
                                                var myPopu = $ionicPopup.show({
                                                    title: "提交失败",
                                                    cssClass: "validate"
                                                });
                                                $timeout(function() {
                                                    myPopu.close();
                                                }, 1000);
                                            }
                                        });
                                        break;
                                    }


                                }


                            });

                            $('#hide_img').attr("src", url);

                        } else {
                            // var rootReq = {
                            //     method: 'post',
                            //     url: $rootScope.rootLocation + '/line/bus/new/feedback',
                            //     data: {
                            //         "cityName": $rootScope.cityName,
                            //         "cityCode": $rootScope.cityCode,
                            //         "feedback": $scope.feedback,
                            //         "contactMethod": $scope.contactMethod
                            //     }
                            // };
                            //
                            // $http(rootReq).then(function (data) {
                            //     if (data.data.head.success == "true") {
                            //         var myPopu = $ionicPopup.show({
                            //             title: "温馨提示",
                            //             template: "反馈意见提交成功",
                            //             cssClass: "validate"
                            //         });
                            //         $timeout(function () {
                            //             myPopu.close();
                            //         }, 2000);
                            //         window.history.back();
                            //     }
                            //
                            // });
                            $.ajax({
                                url: $rootScope.rootLocation + '/line/bus/new/feedback',
                                type: 'POST',
                                data: {
                                    "cityName": $rootScope.cityName,
                                    "cityCode": $rootScope.cityCode,
                                    "feedback": $scope.feedback,
                                    "contactMethod": $scope.contactMethod
                                },
                                success: function(res) {
                                    if (res.head.success == "true") {
                                        var myPopu = $ionicPopup.show({
                                            title: "提交成功",
                                            cssClass: "validate"
                                        });
                                        $timeout(function() {
                                            myPopu.close();
                                            window.history.back();
                                        }, 1000);

                                    } else {
                                        var myPopu = $ionicPopup.show({
                                            title: "提交失败",
                                            cssClass: "validate"
                                        });
                                        $timeout(function() {
                                            myPopu.close();
                                        }, 1000);
                                    }
                                    $scope.tag = true;
                                },
                                error: function(res) {
                                    $scope.tag = true;
                                }
                            });
                        }


                        // var myPopu = $ionicPopup.show({
                        //     title: "温馨提示",
                        //     template: "反馈意见提交成功",
                        //     cssClass: "validate"
                        // });
                        // $timeout(function () {
                        //     myPopu.close();
                        // }, 2000);
                        // window.history.back();


                    }
                    $scope.look = function() {
                        $('#file').click();
                    }
                }]);

})();

// (function(){
// 	"use strict";

// 	wx.config({
// 	debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
// 	appId: 'wxc69f81de77b897c9', // 必填，公众号的唯一标识
// 	timestamp: , // 必填，生成签名的时间戳
// 	nonceStr: '', // 必填，生成签名的随机串
// 	signature: '',// 必填，签名，见附录1
// 	jsApiList: [] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
// 	});

// })(